简体   繁体   English

SQL Group by Date Range

[英]SQL Group by Date Range

I have the following data: 我有以下数据:

Date        Code
2014-08-01  A
2014-08-02  A
2014-08-03  A
2014-08-04  A
2014-08-05  A
2014-08-06  A
2014-08-07  A
2014-08-08  XXXX
2014-08-09  XXXX
2014-08-10  BB
2014-08-11  CCC
2014-08-12  CCC
2014-08-13  CCC
2014-08-14  CCC
2014-08-15  CCC
2014-08-16  CCC
2014-08-17  CCC
2014-08-18  XXXX
2014-08-19  XXXX
2014-08-20  XXXX
2014-08-21  XXXX
2014-08-22  XXXX
2014-08-23  XXXX
2014-08-24  XXXX
2014-08-25  XXXX
2014-08-26  XXXX
2014-08-27  XXXX
2014-08-28  XXXX
2014-08-29  XXXX
2014-08-30  XXXX
2014-08-31  XXXX

I want to group the data with codes but also with date ranges so that the output becomes: 我想用代码对数据进行分组,但也要使用日期范围,以便输出变为:

Min Date    Max Date    Code
2014-08-01  2014-08-07  A
2014-08-08  2014-08-09  XXXX
2014-08-10  2014-08-10  BB
2014-08-11  2014-08-17  CCC
2014-08-18  2014-08-31  XXXX

I have thought about it but cannot think of how to group this data using SQL. 我已经考虑过了,但想不出如何使用SQL对这些数据进行分组。 Any ideas? 有任何想法吗? Thanks! 谢谢!

So, you want to find sequences according to the date that are the same. 因此,您希望根据相同的日期查找序列。

Here is a trick: if you take the difference between row_number() over the entire group and row_number() partitioned by code , then it will be constant for adjacent rows with the same code. 下面是一招:如果你把之间的差值row_number()在整个组和row_number()由分配code ,那么这将是用于与相同的码相邻行恒定。 The rest is just aggregation: 其余的只是聚合:

select  min(date), max(date), code
from (select t.*,
             (row_number() over (order by date) -
              row_number() over (partition by code order by date)
             ) as grpid
      from followingdata t
     ) t
group by grpid, code;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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