如何在mysql中按名称和运行日期分组

jrcvhitl  于 2021-06-17  发布在  Mysql
关注(0)|答案(2)|浏览(287)

我想通过mysql查询来按名称和连续日期对数据进行分组,但我不确定该怎么做。

Date                 |   Name
--------------------------------
2018-10-13 00:00:00  Charles
2018-10-14 00:00:00  Charles
2018-10-15 00:00:00  Charles
2018-10-16 00:00:00  Charles
2018-10-17 00:00:00  Charles
2018-10-18 00:00:00  Charles
2018-12-19 00:00:00  Charles
2018-12-20 00:00:00  Charles
2018-12-21 00:00:00  Charles
2018-12-22 00:00:00  Charles
2018-12-23 00:00:00  Charles
2018-12-24 00:00:00  Charles
2018-12-25 00:00:00  Charles
2018-12-26 00:00:00  Charles
2018-12-27 00:00:00  Charles
2018-12-28 00:00:00  Charles
2018-12-29 00:00:00  Charles
2018-12-30 00:00:00  Charles
2018-12-31 00:00:00  Charles
2019-01-01 00:00:00  Charles
2019-01-02 00:00:00  Charles
2019-01-03 00:00:00  Charles

预期的结果是这样的

Name    | Date From  | Date To   |
----------------------------
Charles | 2018-10-13 | 2018-10-18|
        | 2018-12-19 | 2019-01-03|
z4iuyo4d

z4iuyo4d1#

我怀疑,通过引入公共表表达式,这个过程会大大简化,但我还没有掌握这些(也许是新年决心)。同时,这里有一个想法。。。

DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(dt DATE NOT NULL PRIMARY KEY);

INSERT INTO my_table VALUES
('2018-10-13'),
('2018-10-14'),
('2018-10-15'),
('2018-10-16'),
('2018-10-17'),
('2018-10-18'),
('2018-12-19'),
('2018-12-20'),
('2018-12-21'),
('2018-12-22'),
('2018-12-23'),
('2018-12-24'),
('2018-12-25'),
('2018-12-26'),
('2018-12-27'),
('2018-12-28'),
('2018-12-29'),
('2018-12-30'),
('2018-12-31'),
('2019-01-01'),
('2019-01-02'),
('2019-01-03'); 

SELECT MIN(dt) range_start
     , MAX(dt) range_end 
  FROM
     (
       SELECT x.* 
            , CASE WHEN dt = @prev + INTERVAL 1 DAY THEN @i:=@i ELSE @i:=@i+1 END i
            , @prev := dt 
         FROM my_table x
            , (SELECT @prev := null,@i:=0) vars 
        ORDER 
           BY dt
     ) a
 GROUP 
    BY i;
+-------------+------------+
| range_start | range_end  |
+-------------+------------+
| 2018-10-13  | 2018-10-18 |
| 2018-12-19  | 2019-01-03 |
+-------------+------------+
wgeznvg7

wgeznvg72#

您可以修改此解决方案:

select a.name, adate start_date,bdate enddate from
(select min(yourdate) adate,MIN(REPLACE(yourdate,'-','')),yourdate, name from your_table  GROUP BY SUBSTRING(yourdate FROM 1 FOR 4)) a
left join
(select max(yourdate) bdate,max(REPLACE(yourdate ,'-','')),yourdate ,name from your_table GROUP BY SUBSTRING(yourdate FROM 1 FOR 4)) b
on SUBSTRING(b.yourdate FROM 1 FOR 4) = SUBSTRING(a.yourdate FROM 1 FOR 4)

相关问题