在MySql中使用Case的时隙

时间:2015-03-09 09:25:30

标签: mysql sql case

我正在尝试使用此代码在3个时段对字段求和:

SELECT 
CASE when TIME(v.time) between cast('00:00:00' as time) and cast('06:00:00' as time) then '00:00:00 - 06:00:00'
when TIME(v.time) between cast('06:00:00' as time) and cast('16:00:00' as time) then '06:00:00 - 16:00:00'
when TIME(v.time) between cast('16:00:00' as time) and cast('00:00:00' as time) then '16:00:00 - 00:00:00' End as 'TimeSlot',
sum(v.resting)
FROM vital_activity_histogram v
GROUP BY 'TimeSlot'

我想要的结果是(例如):

time slot              | Sum(v.resting)
00:00:00 - 06:00:00        24
06:00:00 - 16:00:00        56
16:00:00 - 00:00:00        72

运行查询时得到的是:

time slot              | Sum(v.resting)
00:00:00 - 06:00:00        24

我在其他时段内有数据。 有人知道怎么修这个东西吗? 谢谢!

1 个答案:

答案 0 :(得分:1)

您需要GROUP BY TimeSlot,而不是GROUP BY 'TimeSlot':因为您需要对字符串文字进行分组,这是常量(因此每个记录都在同一个组中)。

另见When to use single quotes, double quotes, and backticks in MySQL