SQL 编写显示日期之间跳过的查询
SQL write query that show the skipping between dates
我尝试编写一个查询,通过显示跳跃开始前的日期和跳过后的第一个日期来查找跳跃。
我试过了:
SELECT OrderDate FROM Orders
我得到了:
但我没有成功地将它们分成这样的空隙:
我该怎么做?
使用可以使用dense_rank()
生成一个序列。当您从日期中减去它时,您将识别相邻的连续日期。
所以:
select min(orderdate), max(orderdate)
from (select o.*, dense_rank() over (order by orderdate) as seqnum
from orders o
) o
group by dateadd(day, -seqnum, orderdate)
order by min(orderdate);
您需要 dense_rank()
,因为您的数据有重复项。
编辑:
要查找跳跃,请使用 LEAD()
:
select dateadd(day, 1, orderdate),
dateadd(day, -1, next_orderdate)
from (select orderdate, lead(orderdate) over (order by orderdate) as next_orderdate
from (select distinct orderdate orders o) o
) o
where next_orderdate > dateadd(day, 1, orderdate);
试试这个:
with cte as (select ROW_NUMBER() OVER(ORDER BY OrderDate) as row_num,OrderDate from orders)
select
curr.OrderDate as Gap_start,
nex.OrderDate as Gap_end
from
cte curr
left join
cte nex
on
curr.row_num = nex.row_num - 1;
我尝试编写一个查询,通过显示跳跃开始前的日期和跳过后的第一个日期来查找跳跃。
我试过了:
SELECT OrderDate FROM Orders
我得到了:
但我没有成功地将它们分成这样的空隙:
我该怎么做?
使用可以使用dense_rank()
生成一个序列。当您从日期中减去它时,您将识别相邻的连续日期。
所以:
select min(orderdate), max(orderdate)
from (select o.*, dense_rank() over (order by orderdate) as seqnum
from orders o
) o
group by dateadd(day, -seqnum, orderdate)
order by min(orderdate);
您需要 dense_rank()
,因为您的数据有重复项。
编辑:
要查找跳跃,请使用 LEAD()
:
select dateadd(day, 1, orderdate),
dateadd(day, -1, next_orderdate)
from (select orderdate, lead(orderdate) over (order by orderdate) as next_orderdate
from (select distinct orderdate orders o) o
) o
where next_orderdate > dateadd(day, 1, orderdate);
试试这个:
with cte as (select ROW_NUMBER() OVER(ORDER BY OrderDate) as row_num,OrderDate from orders)
select
curr.OrderDate as Gap_start,
nex.OrderDate as Gap_end
from
cte curr
left join
cte nex
on
curr.row_num = nex.row_num - 1;