在上图中,我想在连续的几天中合并具有相同值的行。 合并的行的最早日期在自列,最新的日期在至列。 在示例中,即使第3行和第4行具有相同的值,由于日期间隔,它们也没有合并。
我尝试使用LAG和LEAD函数,但是没有运气。
答案 0 :(得分:2)
您可以尝试以下方式-
with c as
(
select *, datediff(dd,todate,laedval) as leaddiff,
datediff(dd,todate,lagval) as lagdiff
from
(
select *,lead(todate) over(partition by value order by todate) laedval,
lag(todate) over(partition by value order by todate) lagval
from t1
)A
)
select * from
(
select value,min(todate) as fromdate,max(todate) as todate from c
where coalesce(leaddiff,0)+coalesce(lagdiff,0) in (1,-1)
group by value
union all
select value,fromdate,todate from c
where coalesce(leaddiff,0)+coalesce(lagdiff,0)>1 or coalesce(leaddiff,0)+coalesce(lagdiff,0)<-1
)A order by value
输出:
value fromdate todate
1 16/07/2019 00:00:00 17/07/2019 00:00:00
3 21/07/2019 00:00:00 26/07/2019 00:00:00
2 18/07/2019 00:00:00 18/07/2019 00:00:00
2 20/07/2019 00:00:00 20/07/2019 00:00:00
答案 1 :(得分:1)
我将推荐以下方法:
(define (identity x) x)
(define (foldrecl f x u)
(if (null? x)
u
(identity (foldrecl f (cdr x) (f (car x) u)))))
与该行中的todate
进行比较来实现此目的。这可以使用窗口函数和聚合来处理:
fromdate
Here是db <>小提琴。