基于同一天获取n个数据(时间戳)

时间:2015-06-16 19:55:06

标签: mysql timestamp date

我有这张桌子"传感器"有这些领域:

  • id(int,PK)
  • 时间戳(时间戳)
  • 纬度(varchar)
  • 经度(varchar)
  • data(float)

在一个查询中,我希望获得同一天的5行。请注意,它不是当前日期,数据有很多不同的日期。所以,如果他们在同一天,我想得到他们.. 我尝试使用INTERVAL,但它不起作用。谢谢

1 个答案:

答案 0 :(得分:2)

假设您希望查看上周传感器数据点的数量

SELECT
    DATE(timestamp) dt,
    COUNT(1) datapoints
FROM sensor
WHERE
    timestamp >= DATE(NOW()) - INTERVAL 1 WEEK + INTERVAL 0 SECOND
GROUP BY DATE(timestamp);

白天看这个月

SELECT
    DATE(timestamp) dt,
    COUNT(1) datapoints
FROM sensor
WHERE
    timestamp >= DATE(NOW()) - INTERVAL (DAY(NOW())-1) WEEK + INTERVAL 0 SECOND
GROUP BY DATE(timestamp);

白天看今年

SELECT
    DATE(timestamp) dt,
    COUNT(1) datapoints
FROM sensor
WHERE
    timestamp >= MAKEDATE(YEAR(NOW()),1)
GROUP BY DATE(timestamp);

要逐年查看

SELECT
    DATE(timestamp - INTERVAL (DAY(timestamp)-1) DAY) dt,
    COUNT(1) datapoints
FROM sensor
WHERE
    timestamp >= MAKEDATE(YEAR(NOW()),1)
GROUP BY DATE(timestamp - INTERVAL (DAY(timestamp)-1) DAY);