如何在SQL Server中透视日期范围?

时间:2018-04-18 20:51:06

标签: sql sql-server

我有这样的数据集:

sID   Key   date 
-----------------------
AAA   123   2009-05-27 
AAA   457   1985-01-01
BBB   890   1900-01-01
BBB   785   2008-09-05

我想要一个透视的日期视图,它应该是这样的:

sID   Key   start_date   end_date
-----------------------------------
AAA   123   2009-05-27   2050-12-30
AAA   457   1985-01-01   2009-05-26

第二列的结束日期不应与第一列的开始日期重叠。第一列的结束日期只是我选择的随机日期

2 个答案:

答案 0 :(得分:1)

假设您使用SQL Server 2012+并且输入表没有任何给定ID的重复日期,您可以使用lead分析函数:

select sID
     , Key
     , start_date
     , lead(dateadd(day, -1, start_date) -- one day before the `start_date`
            , 1, '99990101')             -- from the "next" row (or a special value if this is the last row)
         over (partition by sID          -- grouping rows by sID
               order by start_date asc)  -- "next" row assuming ordering by ascending start_date
       as end_date
from ...

答案 1 :(得分:0)

我怀疑你想要lag()功能

select sid, Key, date as start_date,
       lag(dateadd(day,-1,[date]), 1, <default_date>) 
                   over(partition by sid order by ?) as end_date
from table t;

?指定您的实际排序列。