将后续日期分组到 bin 中
Grouping subsequent dates into bins
假设我有以下 table:
date version
2015-02-01 v1
2015-02-02 v1
2015-02-03 v1
2015-02-04 v1
2015-02-02 v2
2015-02-03 v2
2015-02-08 v1
2015-02-09 v1
我的查询应按照我得到的结果对日期进行分组:
datefrom dateto version
2015-02-01 2015-02-04 v1
2015-02-08 2015-02-09 v1
2015-02-02 2015-02-03 v2
我尝试了
LEAD(date) OVER(PARTITION BY version ORDER BY date)
但它并没有真正得到回报,因为我无法对日期 "bins" 进行分组。
我想将每个后续日期分组到 bin 中,不允许日期间隔。
您可以通过将行号与 datediff 与固定日期进行比较来执行此操作,如果这些差异发生变化,则必须至少有一天的间隔。所以,像这样:
select
version,
min (date) as datefrom,
max (date) as dateto
from
(
select
version,
date,
datediff(day, '20100101', date)
- row_number() over (partition by version order by date) as bin
from
version
) T
group by
version,
bin
order by
version,
datefrom
假设我有以下 table:
date version
2015-02-01 v1
2015-02-02 v1
2015-02-03 v1
2015-02-04 v1
2015-02-02 v2
2015-02-03 v2
2015-02-08 v1
2015-02-09 v1
我的查询应按照我得到的结果对日期进行分组:
datefrom dateto version
2015-02-01 2015-02-04 v1
2015-02-08 2015-02-09 v1
2015-02-02 2015-02-03 v2
我尝试了
LEAD(date) OVER(PARTITION BY version ORDER BY date)
但它并没有真正得到回报,因为我无法对日期 "bins" 进行分组。 我想将每个后续日期分组到 bin 中,不允许日期间隔。
您可以通过将行号与 datediff 与固定日期进行比较来执行此操作,如果这些差异发生变化,则必须至少有一天的间隔。所以,像这样:
select
version,
min (date) as datefrom,
max (date) as dateto
from
(
select
version,
date,
datediff(day, '20100101', date)
- row_number() over (partition by version order by date) as bin
from
version
) T
group by
version,
bin
order by
version,
datefrom