在SQL中确定行程的“开始”和“结束”日期?

时间:2019-05-27 05:55:04

标签: sql db2

我想从下表中获取行程的开始日期和结束日期-

enter image description here

我尝试了最小(日期),然后尝试最大(日期)按Line_Number,国家/地区分组 也 LEAD功能

首选结果

enter image description here

1 个答案:

答案 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;
相关问题