2017-03-29 66 views
1

這是我的源表複雜的SQL改造

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 

Ineed以下輸出

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) 

任何建議如何可以做到這一點?

+2

不要標記不涉及的產品。把一個標籤放回去,就是你使用的dbms標籤。 – jarlh

+1

我可以建議來源上的左連接嗎? –

+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 
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') 
+0

不適用於所有數據庫產品。 Sql server僅在2012版本開始支持滯後和領先。我不知道Oracle或Sqlite。 –

+0

我有SQL 2008所以沒有工作 –

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 
0

這將在Oracle版本工作從9I:

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排序以確保正確的值即