小组记录15分钟

时间:2012-11-24 10:16:26

标签: mysql ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.1

我希望使用以下查询基于时间戳列每15分钟对记录进行分组,但前两个记录差异仅在10分钟内。

RAILS CODE:

select("DATE_FORMAT(reading_on,'%H:%i') as date,
  ROUND(UNIX_TIMESTAMP(reading_on)/(900)) as fif ,
  max(power) as total").group("fif").where("imei= #{site}" ).order("fif asc")

MYSQL QUERY:

SELECT DATE_FORMAT(reading_on,'%H:%i') as date,
  ROUND(UNIX_TIMESTAMP(reading_on)/(900)) as fif ,
  max(power) as total FROM `clarodetails` 
WHERE (imei= 353469040778516) 
  AND (date(reading_on) between '2012-11-18 00:00:00' 
  AND '2012-11-18 23:59:59') 
GROUP BY fif 
ORDER BY fif asc LIMIT 15

输出: OUPPUT

2 个答案:

答案 0 :(得分:1)

你可以用这个:

SELECT
  DATE_FORMAT(
    FROM_UNIXTIME(UNIX_TIMESTAMP(reading_on) -
      MOD(UNIX_TIMESTAMP(reading_on), 900)), '%H:%i') as fif,
  max(power) as total
FROM `clarodetails` 
WHERE
  (imei= 353469040778516) 
  AND (date(reading_on) >= '2012-11-18')
  AND (date(reading_on) <  '2012-11-19') 
GROUP BY fif 
ORDER BY fif asc LIMIT 15

我也不想使用between '2012-11-18 00:00:00' and '2012-11-18 23:59:59'(在23:59:59之后但在午夜之前,你总是会错过reading_on的一些记录...)

答案 1 :(得分:0)

这可能是由于聚合和非聚合功能的混合。第一个结果列未聚合,因此结果集显示查询遇到的此列的第一个值。在聚合中包含日期列:

...GROUP BY fif, date...