我有一个非常简单的 MySQL 表
Name | Time | Count
James | 11:00 | 10
Simon | 11:00 | 5
James | 11:30 | 4
Oliver| 11:30 | 2
James | 12:00 | 1
etc.
我想创建一个 MySQL 查询,它将每个人的 Count 相加并输出最后 1 小时值、最后 3 小时值、最后 6 小时值、最后 12 小时值和最后 24 小时值。
例如,如果现在是 12:59,上表将输出:
Name | Last-1 | Last-3 | Last-6
James | 1 | 15 | 15
Simon | 0 | 5 | 5
Oliver| 0 | 2 | 2
是否可以在单个查询中执行此操作?到目前为止,我有:
SELECT name, HOUR( NOW( ) ) - HOUR( time ) AS lasthours, SUM( count ) AS c
FROM table
GROUP BY name, lasthours
HAVING lasthours =0
ORDER BY c DESC
这给了我过去一个小时,但我如何获得额外的列?
非常感谢任何帮助。
编辑:
接受的答案需要稍微调整一下,结果如下:
SELECT name ,
SUM( IF( HOUR( TIMEDIFF( NOW( ) , time ) ) <=0, count , 0 ) ) AS `Last hour` ,
SUM( IF( HOUR( TIMEDIFF( NOW( ) , time ) ) <=3, count , 0 ) ) AS `Last 3 hours` ,
SUM( IF( HOUR( TIMEDIFF( NOW( ) , time ) ) <=6, count , 0 ) ) AS `Last 6 hours` ,
SUM( IF( HOUR( TIMEDIFF( NOW( ) , time ) ) <=12, count , 0 ) ) AS `Last 12 hours` ,
SUM( IF( HOUR( TIMEDIFF( NOW( ) , time ) ) <=24, count , 0 ) ) AS `Last 24 hours` ,
SUM( IF( HOUR( TIMEDIFF( NOW( ) , time ) ) <=48, count , 0 ) ) AS `Last 2 days` ,
SUM( IF( HOUR( TIMEDIFF( NOW( ) , time ) ) <=72, count , 0 ) ) AS `Last 3 days` ,
SUM( IF( HOUR( TIMEDIFF( NOW( ) , time ) ) <=96, count , 0 ) ) AS `Last 4 days` ,
SUM( IF( HOUR( TIMEDIFF( NOW( ) , time ) ) <=120, count , 0 ) ) AS `Last 5 days` ,
SUM( IF( HOUR( TIMEDIFF( NOW( ) , time ) ) <=144, count , 0 ) ) AS `Last 6 days` ,
SUM( IF( HOUR( TIMEDIFF( NOW( ) , time ) ) <=168, count , 0 ) ) AS `Last week`
FROM table
GROUP BY name
ORDER BY `Last hour` DESC