在SQLite中添加具有相同日期的行

时间:2015-02-21 01:38:10

标签: sql sqlite

我试图添加一周中同一天的值

我的查询:

SELECT c.CounterID,
total(CASE WHEN strftime('%w', c.Date) = 1 THEN c.Value ELSE 0 END) AS Monday,
total(CASE WHEN strftime('%w', c.Date) = 2 THEN c.Value ELSE 0 END) AS Tuesday,
total(CASE WHEN strftime('%w', c.Date) = 3 THEN c.Value ELSE 0 END) AS Wednesday,
total(CASE WHEN strftime('%w', c.Date) = 4 THEN c.Value ELSE 0 END) AS Thursday,
total(CASE WHEN strftime('%w', c.Date) = 5 THEN c.Value ELSE 0 END) AS Friday,
total(CASE WHEN strftime('%w', c.Date) = 6 THEN c.Value ELSE 0 END) AS Saturday,
total(CASE WHEN strftime('%w', c.Date) = 0 THEN c.Value ELSE 0 END) AS Sunday
FROM CounterItems c
GROUP BY c.CounterID

对于每周的每一天列,上面返回0。为什么不把它们加起来?

编辑:下面是我的表结构

ID|CounterID|Value|Date

EDIT2:这是日期格式2015-02-13 01:07:21

1 个答案:

答案 0 :(得分:1)

尝试将CAST() strftime功能转移到Integer。见下文:

SELECT c.CounterID,
       TOTAL(CASE WHEN CAST(strftime('%w', c.Date) AS INTEGER) = 1 THEN c.Value ELSE 0 END) AS Monday,
       TOTAL(CASE WHEN CAST(strftime('%w', c.Date) AS INTEGER) = 2 THEN c.Value ELSE 0 END) AS Tuesday,
       TOTAL(CASE WHEN CAST(strftime('%w', c.Date) AS INTEGER) = 3 THEN c.Value ELSE 0 END) AS Wednesday,
       TOTAL(CASE WHEN CAST(strftime('%w', c.Date) AS INTEGER) = 4 THEN c.Value ELSE 0 END) AS Thursday,
       TOTAL(CASE WHEN CAST(strftime('%w', c.Date) AS INTEGER) = 5 THEN c.Value ELSE 0 END) AS Friday,
       TOTAL(CASE WHEN CAST(strftime('%w', c.Date) AS INTEGER) = 6 THEN c.Value ELSE 0 END) AS Saturday,
       TOTAL(CASE WHEN CAST(strftime('%w', c.Date) AS INTEGER) = 0 THEN c.Value ELSE 0 END) AS Sunday
FROM CounterItems c
GROUP BY c.CounterID