1

我有以下 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

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

如何更改 SQL 语句,以便在具有适当字段名称的同一记录中获得语言总计?例如:

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

在此处输入图像描述

以下是表格:

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)
4

1 回答 1

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 
于 2012-07-31T10:18:42.397 回答