如何通过一个查询从上一小时,最后一天和上个月获取数据?

时间:2015-01-23 14:22:41

标签: mysql sql database pdo

我正在记录已经发送到我的API的查询:

id  |  timestamp
----+---------------------
1   |  2015-01-19 18:01:47
2   |  2015-01-19 20:41:37
3   |  2015-01-20 14:15:06
4   |  2015-01-21 13:02:51
5   |  2015-01-23 05:02:12

现在,我需要知道在过去的60分钟,24小时和30天内进行了多少查询,并将其分组:

HOURLY | DAILY | MONTHLY
-------+-------+--------
0      | 1     | 5

这可以在一个查询中完成吗?

修改

我已经使用了这里的建议并对逻辑事物进行了一些操作,直到它按照我想要的方式工作。

SELECT SUM(CASE WHEN DATE_SUB(NOW(), interval 1 HOUR) <= `TIMESTAMP` THEN 1 ELSE 0 END) HOURLY,
       SUM(CASE WHEN DATE_SUB(NOW(), interval 1 DAY) <= `TIMESTAMP` THEN 1 ELSE 0 END) DAILY,
       SUM(CASE WHEN DATE_SUB(NOW(), interval 1 MONTH) <= `TIMESTAMP` THEN 1 ELSE 0 END) MONTHLY
FROM `REQUESTS`;

非常感谢你的帮助!

3 个答案:

答案 0 :(得分:8)

select sum(timestamp >= now() - interval 1 hour) as hour,
       sum(timestamp >= now() - interval 1 day) as day,
       sum(timestamp >= now() - interval 1 month) as month
from your_table

SQLFiddle demo

答案 1 :(得分:8)

select sum(case when timestamp between now() - interval 1 hour and now() then 1 else 0) hourly,
       sum(case when timestamp between now() - interval 1 day and now() then 1 else 0) daily,
       sum(case when timestamp between now() - interval 1 month and now() then 1 else 0) monthly
from   your_table

编辑...

答案 2 :(得分:0)

你可以在这里使用的另一个巧妙的技巧是SUM()函数,里面只有一个布尔表达式。当你这样做时,MySQL将有效地计算满足条件的行数。所以,通过使用类似的东西:

SUM(timeCol >= (NOW() - INTERVAL 1 HOUR))

它只计算在过去一小时内有时间戳的行数。试试这个问题:

SELECT SUM(timecol >= (NOW() - INTERVAL 1 HOUR)) AS hourly,
  SUM(timeCol >= (NOW() - INTERVAL 1 DAY)) AS daily,
  SUM(timeCol >= (NOW() - INTERVAL 1 MONTH)) AS monthly
FROM myTable;

它在SQL Fiddle中为我工作。

修改

如果您的表 具有未来日期,则上述解决方案不起作用,因此如果您想确保您只获得过去一小时,一天或一个月的值,那么< em>不超过当前时间,只需添加where子句:

SELECT SUM(timecol >= (NOW() - INTERVAL 1 HOUR)) AS hourly,
  SUM(timeCol >= (NOW() - INTERVAL 1 DAY)) AS daily,
  SUM(timeCol >= (NOW() - INTERVAL 1 MONTH)) AS monthly
FROM myTable
WHERE timeCol <= NOW();

以下是更新的Fiddle,其中包含无效记录,表明其有效。