0

我有一个非常简单的 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
4

2 回答 2

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上查看。

于 2012-06-29T11:40:38.803 回答
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 
于 2012-06-29T11:41:11.240 回答