简体   繁体   中英

How to group by day/month/year on a subquery

I have a simple table like this (in real x-thousand values):

在此处输入图片说明

On this table I'm doing a query to get the differences (which works fine):

select
  EL.sensor_id,
  EL.value_id,
  EL.time,
  EL.value,
  if( @lastSN = EL.sensor_id, EL.value - @lastValue, 0000.00 ) as diff,
  @lastSN := EL.sensor_id,
  @lastValue := EL.value
from
      data_test_debug EL,
      ( select @lastSN := 0,
               @lastValue := 0 ) SQLVars
   where EL.value_id = "gas"
   order by
      EL.sensor_id,
      EL.time

The result looks like this:

在此处输入图片说明

Now I have a problem because I have to group the diff data.

by day or month or week or year (for representing the data in charts)

I tried something like this:

select MONTHNAME(EL.time), SUM(EL.diff)
FROM data_test_debug EL,

(select
      EL.sensor_id,
      EL.value_id,
      EL.time,
      EL.value,
      if( @lastSN = EL.sensor_id, EL.value - @lastValue, 0000.00 ) as diff,
      @lastSN := EL.sensor_id,
      @lastValue := EL.value
   from
      data_test_debug EL,
      ( select @lastSN := 0,
               @lastValue := 0 ) SQLVars
   where EL.value_id = "gas"
   order by
      EL.sensor_id,
      EL.time) AS t
GROUP BY YEAR(EL.time), MONTH(EL.time)

but had no look to get results..

The data is hourly collected therefore grouping is needed.

Don't join the table again. Apply the grouping directly to the subquery:

SELECT YEAR(time), MONTHNAME(time), SUM(diff)
FROM (select EL.sensor_id,
             EL.value_id,
             EL.time,
             EL.value,
             if(@lastSN = EL.sensor_id, EL.value - @lastValue, 0.0) as diff,
             @lastSN := EL.sensor_id,
             @lastValue := EL.value
      FROM data_test_debug EL, (SELECT @lastSN := 0,
                                @lastValue := 0) SQLVars
      WHERE EL.value_id = "gas"
      ORDER BY EL.sensor_id, EL.time
     ) AS t
GROUP BY YEAR(time), MONTH(time)

It can be greatly simplified by removing all those fields that you're not using, but you can do that after you get it working.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM