¿Cómo devolver múltiples registros de un JOIN como columnas?

I have the following SQL statement (SQLite 3.0) which is joining two tables, the results are that I have a record per day with totals for the day, but joining it to the language table, it gives me five records per day, one for each language.

SELECT 
re.day,
re.flashcardsAdded,
re.flashcardsTested,
re.flashcardsLearned,
re.totalPoints AS totalForDay,
la.language,
la.total AS totalForLanguage

FROM dpod_site_reportDays AS re
JOIN dpod_site_reportDayLanguageTotals AS la ON re.day=la.day
ORDER BY re.day DESC

Sin embargo, I want only one record per day and instead of e.g. "french" being data, I want it to be a column name with the total for that language as the data for that column.

How can I change the SQL statement so that I get the language totals in the same record with appropriate field names? p.ej:

day | flashcardsAdded | flashcardsTested | flashcardsLearned | totalForDay | french | german | italian | russian | german

enter image description here

Aquí están las tablas:

CREATE TABLE dpod_site_reportDayLanguageTotals(
day VARCHAR(50), 
language VARCHAR(1024), 
total INT(12), 
extras VARCHAR(1024), 
idCode VARCHAR(1024), 
whenCreated VARCHAR(50), 
whenChanged VARCHAR(50), 
id INTEGER PRIMARY KEY  AUTOINCREMENT  NOT NULL  UNIQUE)

CREATE TABLE dpod_site_reportDays(
day VARCHAR(50), 
flashcardsAdded INT(12), 
flashcardsTested INT(12), 
flashcardsLearned INT(12), 
journalPoints INT(12), 
readingPoints INT(12), 
correctionPoints INT(12), 
extrasData TEXT, 
totalPoints INT(12), 
extras VARCHAR(1024), 
idCode VARCHAR(1024), 
whenCreated VARCHAR(50), 
whenChanged VARCHAR(50), 
id INTEGER PRIMARY KEY  AUTOINCREMENT  NOT NULL  UNIQUE)

preguntado el 31 de julio de 12 a las 11:07

I think you forgot the SQL statement ;) -

@EdwardTanguay Shame you're not using a platform that supports PIVOT :) -

Interesting, didn't know PIVOT was in SQL Server, but a database-as-file also has its convenient advantages. :-) -

1 Respuestas

SELECT  
re.day, 
re.flashcardsAdded, 
re.flashcardsTested, 
re.flashcardsLearned, 
re.totalPoints AS totalForDay, 
Sum(CASE la.language WHEN 'french' THEN  la.total ELSE 0 END) AS french, 
Sum(CASE la.language WHEN 'german' THEN  la.total ELSE 0 END) AS german, 
Sum(CASE la.language WHEN 'italian' THEN  la.total ELSE 0 END) AS italian, 
Sum(CASE la.language WHEN 'russian' THEN  la.total ELSE 0 END) AS russian


FROM dpod_site_reportDays AS re 
JOIN dpod_site_reportDayLanguageTotals AS la ON re.day=la.day
GROUP BY re.day, 
re.flashcardsAdded, 
re.flashcardsTested, 
re.flashcardsLearned, 
re.totalPoints
ORDER BY re.day DESC 

Respondido 31 Jul 12, 11:07

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.