我如何按间隔的组对SQL查询中的结果进行分组?

时间:2015-08-26 06:29:49

标签: mysql sql group-by grouping

我在mysql表中有以下数据

|id|value|date|
|1|88|2015-08-26 08:00:00|
|2|88|2015-08-26 09:00:00|
|3|76|2015-08-26 10:00:00|
|4|76|2015-08-26 11:00:00|
|5|88|2015-08-26 12:00:00|
|6|76|2015-08-26 13:00:00|
|7|76|2015-08-26 14:00:00|
|8|76|2015-08-26 15:00:00|
|9|94|2015-08-26 16:00:00|
|10|94|2015-08-26 17:00:00|
|11|63|2015-08-26 18:00:00|
|12|94|2015-08-26 19:00:00|

我想生成以下结果:

|value|min date|max date|
|88|2015-08-26 08:00:00|2015-08-26 09:00:00|
|76|2015-08-26 10:00:00|2015-08-26 11:00:00|
|88|2015-08-26 12:00:00|2015-08-26 12:00:00|
|76|2015-08-26 13:00:00|2015-08-26 15:00:00|
|94|2015-08-26 16:00:00|2015-08-26 17:00:00|
|63|2015-08-26 18:00:00|2015-08-26 18:00:00|
|94|2015-08-26 19:00:00|2015-08-26 19:00:00|

我想按照'日期间隔'对具有相同值的结果进行分组。

为了达到这个结果,我需要编写什么查询?

2 个答案:

答案 0 :(得分:3)

架构:

create table thing1
(   id int not null,
    value int not null,
    dt datetime not null
);
insert thing1 (id,value,dt) values
(1,88,'2015-08-26 08:00:00'),
(2,88,'2015-08-26 09:00:00'),
(3,76,'2015-08-26 10:00:00'),
(4,76,'2015-08-26 11:00:00'),
(5,88,'2015-08-26 12:00:00'),
(6,76,'2015-08-26 13:00:00'),
(7,76,'2015-08-26 14:00:00'),
(8,76,'2015-08-26 15:00:00'),
(9,94,'2015-08-26 16:00:00'),
(10,94,'2015-08-26 17:00:00'),
(11,63,'2015-08-26 18:00:00'),
(12,94,'2015-08-26 19:00:00');

查询:

set @grp := 0, @value:=0;
select value,min(dt) as min_date,max(dt) as max_date
from 
( 
  select id,value,dt,
      @grp := if(@value <> value, @grp + 1, @grp) as grouping,
      @value := value as drewisdummy
  from thing1
  order by id
) xxx
group by grouping

结果:

+-------+---------------------+---------------------+
| value | min_date            | max_date            |
+-------+---------------------+---------------------+
|    88 | 2015-08-26 08:00:00 | 2015-08-26 09:00:00 |
|    76 | 2015-08-26 10:00:00 | 2015-08-26 11:00:00 |
|    88 | 2015-08-26 12:00:00 | 2015-08-26 12:00:00 |
|    76 | 2015-08-26 13:00:00 | 2015-08-26 15:00:00 |
|    94 | 2015-08-26 16:00:00 | 2015-08-26 17:00:00 |
|    63 | 2015-08-26 18:00:00 | 2015-08-26 18:00:00 |
|    94 | 2015-08-26 19:00:00 | 2015-08-26 19:00:00 |
+-------+---------------------+---------------------+
7 rows in set (0.00 sec)

答案 1 :(得分:1)

试试这个:

SELECT value, min(date) AS 'min date', max(date) AS 'max date'
FROM yourTable
GROUP BY round((hour(date)/8)+1,0),value

您的搜索结果似乎按当天的季度分组。