我有一个表格(tbl_results),如下所示:
name | time_in_minutes
-------------
jonny | 14
jonny | 27
jonny | 28
jonny | 56
jonny | 57
jonny | 58
sarah | 12
sarah | 16
sarah | 17
sarah | 24
sarah | 25
我想知道如何编写查询(可能是交叉连接?),它总结了特定时间段内的次数。对于上面的例子,我将使用10分钟的时间。所以结果如下。
name | 0-10 | 11-20 | 21-30 | 31-40 | 41-50 | 51-60
jonny | 0 | 1 | 2 | 0 | 0 | 3
sarah | 0 | 3 | 2 | 0 | 0 | 0
我会编写一些代码,但我真的不确定从哪里开始这样的查询。
答案 0 :(得分:2)
使用条件聚合:
SELECT
name,
[0-10] = COUNT(CASE WHEN time_in_minutes BETWEEN 0 AND 10 THEN 1 END),
[11-20] = COUNT(CASE WHEN time_in_minutes BETWEEN 0 AND 10 THEN 1 END),
[21-30] = COUNT(CASE WHEN time_in_minutes BETWEEN 0 AND 10 THEN 1 END),
[31-40] = COUNT(CASE WHEN time_in_minutes BETWEEN 0 AND 10 THEN 1 END),
[41-50] = COUNT(CASE WHEN time_in_minutes BETWEEN 0 AND 10 THEN 1 END),
[51-60] = COUNT(CASE WHEN time_in_minutes BETWEEN 0 AND 10 THEN 1 END)
FROM tbl
GROUP BY name