复杂的SQL转换

时间:2017-03-29 10:25:38

标签: sql sql-server sql-server-2008

这是我的源表

Reference   ModifiedDate
------------------------------------
1023175     2017-03-03 16:02:01.723
1023175     2017-03-07 07:59:49.283
1023175     2017-03-12 11:14:40.230

提示以下输出

Reference   StartDate                 EndDate
---------------------------------------------
1023175   2017-03-03 16:02:01.723     2017-03-07 07:59:49.283
1023175   2017-03-07 07:59:49.283     2017-03-12 11:14:40.230
1023175   2017-03-12 11:14:40.230     9999-12-31 00:00:00.000 (last record should have this value)

有关如何实现这一目标的任何建议?

4 个答案:

答案 0 :(得分:3)

您可以使用超前/滞后窗口功能。它从SQL Server2012开始工作......在此之前,您需要使用genereated row_number进行自联接

select Reference, ModifiedDate as StartDate, 
    lead(ModifiedDate, 1, '9999-12-31 00:00:00.000') over(order by Reference) as EndDate
    from #yourreference

表格详情

create table #yourreference (Reference int, ModifiedDate datetime)

insert into #yourreference (
Reference ,  ModifiedDate ) values
 (1023175   ,'2017-03-03 16:02:01.723')
,(1023175   ,'2017-03-07 07:59:49.283')
,(1023175   ,'2017-03-12 11:14:40.230')

答案 1 :(得分:2)

DECLARE @MyTable TABLE (Reference INT, ModifiedDate DATETIME)
INSERT INTO @MyTable VALUES

(1023175, '2017-03-03 16:02:01.723'),
(1023175, '2017-03-07 07:59:49.283'),
(1023175, '2017-03-12 11:14:40.230');

SELECT
    T1.Reference, 
    T1. ModifiedDate AS Start_Date, 
    COALESCE(MIN(T2.ModifiedDate),CAST('31/12/9999' AS DATETIME))  as EndDate
FROM @MyTable T1
    LEFT JOIN @MyTable T2
ON T1.reference = T2.reference AND T1.ModifiedDate < T2.ModifiedDate 
GROUP BY 
    T1.Reference, 
    T1. ModifiedDate

答案 2 :(得分:0)

 select a.Reference, a.ModifiedDate as StartDate, 
        coalesce(min(b.ModifiedDate),9999-12-31 00:00:00.000)  as EndDate
 from source_table as a
 left join source_table as b
 on a.reference = b.reference and a.ModifiedDate < b.ModifiedDate 
 group by a.Reference, a.ModifiedDate 

答案 3 :(得分:0)

这适用于9i的Oracle版本:

select reference
       , modifieddate as startdate
       , lead ( modifieddate, 1, to_timestamp('9999-12-31 00:00:00.000', 'yyyy-mm-dd hh24:mi:ss.ff3'))
                 over (partition by reference order by modifieddate) as enddate
from your_table;

请注意,窗口子句需要按modifieddate排序以确保正确的值。