如何从JOIN返回多个记录作为列?

时间:2012-07-31 10:12:35

标签: sql sqlite join

我有以下SQL语句(SQLite 3.0),它连接了两个表,结果是我每天都有一个记录,当天的总数,但加入语言表,它给了我五每日记录,每种语言一种。

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

但是,我每天只需要一条记录,而不是例如“french”是数据,我希望它是一个列名,该语言的总数作为该列的数据。

如何更改SQL语句,以便在具有相应字段名称的同一记录中获取语言总数?例如:

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

enter image description here

以下是表格:

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)

1 个答案:

答案 0 :(得分:2)

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