如果其他日期介于两者之间,则将日期范围与单独的组分组
Group Date ranges with separate groups if other date in between
我有一个 Table 这样的:
Specification Date
ADS 2020-09-04 00:00:00.000
ADS 2020-09-05 00:00:00.000
ADS 2020-09-06 00:00:00.000
AZR 2020-09-07 00:00:00.000
AZR 2020-09-08 00:00:00.000
ADS 2020-09-09 00:00:00.000
ADS 2020-09-10 00:00:00.000
我想要 select 开始日期和结束日期,并按规范对它们进行分组。
所以我的输出应该是这样的:
Specification Start End
ADS 2020-09-04 00:00:00.000 2020-09-06 00:00:00.000
AZR 2020-09-07 00:00:00.000 2020-09-08 00:00:00.000
ADS 2020-09-09 00:00:00.000 2020-09-10 00:00:00.000
我试过:
select
Specification, MIN(Date) as Start, MAX(Date) as End
from CUSTOMERS
group by Specification
但这并没有给出我想要的结果。有人有想法吗?
你可以试试下面的 - 这是一个间隙和孤岛问题
select col1, min(dateval) as start, max(dateval) as end
from
(
select *,row_number() over(order by dateval)-
row_number() over(partition by col1 order by dateval) as grp
from t
)A group by col1, grp
我有一个 Table 这样的:
Specification Date
ADS 2020-09-04 00:00:00.000
ADS 2020-09-05 00:00:00.000
ADS 2020-09-06 00:00:00.000
AZR 2020-09-07 00:00:00.000
AZR 2020-09-08 00:00:00.000
ADS 2020-09-09 00:00:00.000
ADS 2020-09-10 00:00:00.000
我想要 select 开始日期和结束日期,并按规范对它们进行分组。 所以我的输出应该是这样的:
Specification Start End
ADS 2020-09-04 00:00:00.000 2020-09-06 00:00:00.000
AZR 2020-09-07 00:00:00.000 2020-09-08 00:00:00.000
ADS 2020-09-09 00:00:00.000 2020-09-10 00:00:00.000
我试过:
select
Specification, MIN(Date) as Start, MAX(Date) as End
from CUSTOMERS
group by Specification
但这并没有给出我想要的结果。有人有想法吗?
你可以试试下面的 - 这是一个间隙和孤岛问题
select col1, min(dateval) as start, max(dateval) as end
from
(
select *,row_number() over(order by dateval)-
row_number() over(partition by col1 order by dateval) as grp
from t
)A group by col1, grp