答案 0 :(得分:0)
差距和岛屿...
尝试一下:
with tab (line_number, date, country) as (values
(123456, date('2019-05-20'), 'London')
, (123456, date('2019-05-21'), 'London')
, (123456, date('2019-05-22'), 'London')
, (123456, date('2019-06-27'), 'London')
, (123456, date('2019-06-28'), 'London')
, (123456, date('2019-06-29'), 'London')
, (123456, date('2019-06-30'), 'London')
, (123456, date('2019-07-01'), 'London')
)
, a as (
select t.*
-- OLAP function sums the "flags" computed below,
-- so each group with consecutive dates has its distinct group number
, sum
(
-- The expression below
-- returns 1 if date of the current row is 1 day after the date of the previous row
-- in the corresponding group (line_number, country) ordered by date
-- and 0 otherwise
case when date = lag(date) over (partition by line_number, country order by date) + 1 day then 0 else 1 end
) over (partition by line_number, country order by date) grp_num
from tab t
)
select
line_number
, min(date) as start_date
, max(date) as end_date
, country
--, grp_num
from a
group by line_number, country, grp_num;