在 MySql 中使用 Case 的时隙

Time slots using Case in MySql

我正在尝试使用以下代码按 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

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

您需要 GROUP BY TimeSlot,而不是 GROUP BY 'TimeSlot':就目前情况而言,您是根据字符串文字进行分组,该文字是常量(因此每条记录都在同一组中)。

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