我有一个非常简单的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小时值。
e.g。如果时间现在是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
答案 0 :(得分:2)
SELECT `name`,
SUM(IF(HOUR(TIMEDIFF(CURTIME(), `Time`)) <= 1, `Count`, 0)) AS `Last-1`,
SUM(IF(HOUR(TIMEDIFF(CURTIME(), `Time`)) <= 3, `Count`, 0)) AS `Last-3`,
SUM(IF(HOUR(TIMEDIFF(CURTIME(), `Time`)) <= 6, `Count`, 0)) AS `Last-6`
FROM `table`
GROUP BY `name`
在sqlfiddle上查看。
答案 1 :(得分:1)
试试这个
Select Name,Sum(Case When Hour(Now)-Hour(Time) <= 1 Then Count Else 0 End) As Last1,
Sum(Case When Hour(Now)-Hour(Time) Between 2 AND 3 Then Count Else 0 End) As Last3,
Sum(Case When Hour(Now)-Hour(Time) Between 4 And 6 Then Count Else 0 End) As Last6
From name
Order By