2015-04-28 78 views
1

僅爲SQL Server 2008尋求優化代碼(因爲LagLead函數在SQL Server 2008中不可用)。對於以下要求(最後一個記錄結束日期爲空或不爲空)分層數據所需的cte實現

業務規則是:

結束日期應該開始日期爲下一條規則,否則規則不應該被認爲是連續的,將被視爲一個其他規則系列,如下例所示,由於第四條記錄和第七條記錄規則已被制動,所以有三個系列。

RuleId Name StartDate   EndDate 
-----------------------------------------------------------  
2  TP1  1/1/2015 00.00.00 1/31/2015 00.00.00 
2  TP1  1/31/2015 00.00.00 2/28/2015 00.00.00 
2  TP1  2/28/2015 00.00.00 3/15/2015 00.00.00 
2  TP1  3/18/2015 00.00.00 11/28/2015 00.00.00 
2  TP1  11/28/2015 00.00.00 4/30/2016 00.00.00 
2  TP1  4/30/2016 00.00.00 10/5/2016 00.00.00 
2  TP1  10/25/2016 00.00.00 11/15/2016 00.00.00 
2  TP1  11/15/2016 00.00.00 Null 

結果應該是以下

2  TP1  1/1/2015 00.00.00 3/15/2015 00.00.00 
2  TP1  3/18/2015 00.00.00 10/5/2016 00.00.00 
2  TP1  10/25/2016 00.00.00 Null 

回答

1

您可以在此基礎上你可以將你的結果做PARTITION BY一個ROW_NUMBER(),然後做一個自我與RN = RN + 1加入,做一個DATEDIFF

嘗試是這樣的

DECLARE @Rules TABLE(RuleId INT,Name CHAR(3), StartDate DATE,   EndDate DATE) 

INSERT INTO @Rules VALUES 
(3 ,'TP3', '3/18/2015', '11/28/2015'), 
(3 ,'TP3', '11/28/2015', '4/30/2016'), 
(3 ,'TP3', '4/30/2016', '10/5/2016'), 
(3 ,'TP3', '10/25/2016', '11/15/2016'), 
(3 ,'TP3', '11/15/2016', null) 


;WITH CTE AS 
(
SELECT ROW_NUMBER() OVER(PARTITION BY RuleID ORDER BY StartDate) rn,* 
FROM @Rules 
), CTE2 AS 
(
SELECT ISNULL(DATEDIFF(day,C1.EndDate,C2.StartDate),0) diff,C1.* 
FROM CTE C1 
LEFT JOIN CTE C2 ON C1.rn + 1 = C2.rn 
AND C1.RuleId = C2.RuleId 
) 
SELECT RuleId,Name,MIN(StartDate) StartDate,NULLIF(MAX(CASE WHEN EndDate IS NULL THEN '2999/12/31' ELSE EndDate END),'2999/12/31') EndDate 
FROM 
(
SELECT C2.Diff,C1.RuleId,C1.Name,C1.StartDate,C1.EndDate 
FROM CTE2 C1 
CROSS APPLY (SELECT ISNULL(SUM(Diff),0) Diff FROM CTE2 C2 WHERE C1.StartDate > C2.StartDate AND C1.RuleId = C2.RuleId) C2 
) C 
GROUP BY RuleId,Name,Diff 
ORDER BY RuleId,Diff 
+0

感謝G8的解決方案,但是,當我試圖測試相同的以下數據範圍內,那麼不考慮第一個記錄 (3,「TP3」,「3/18 (3,'TP3','11/28/2015','4/30/2016'), (3,'TP3','4/30','11/28/2015'), (3,'TP3','10/25/2016','11/15/2016'), (3,'TP3','11/15'/2016',null) 結果開始日期不預期 –

+0

檢查更新的答案 – ughai