我從我的表中有以下記錄稱爲支付。我喜歡做的是根據開始和結束服務日期,利用僅1列日期將每條記錄分成單獨的記錄集。單獨記錄分享日期範圍利用單列日期
DisbursementID ServiceProviderID Original CircuitID Beginning_Service_Date Ending_Service_Date Amount
-------------- ----------------- -------- ----------- ---------------------- ------------------- -----------
53562 673 0 1814 2015-12-01 2015-12-31 531
53563 673 0 1814 2015-11-01 2015-11-30 531
我的目標結果是看起來像
DisbursementID ServiceProviderID Original CircuitID Date Range Amount
-------------- ----------------- -------- ----------- ---------- -------
53562 673 0 1814 2015-12-01 531
53562 673 0 1814 2015-12-02 531
53562 673 0 1814 2015-12-03 531
53562 673 0 1814 2015-12-04 531
53562 673 0 1814 2015-12-05 531
53563 673 0 1814 2015-11-01 531
53563 673 0 1814 2015-11-02 531
53563 673 0 1814 2015-11-03 531
53563 673 0 1814 2015-11-04 531
53563 673 0 1814 2015-11-05 531
而不是我的結果看起來像
DisbursementID ServiceProviderID Original CircuitID Date Range Amount
-------------- ----------------- -------- ----------- ---------- -------
53562 673 0 1814 2015-12-01 531
53563 673 0 1814 2015-11-01 531
53563 673 0 1814 2015-11-02 531
53563 673 0 1814 2015-11-03 531
53563 673 0 1814 2015-11-04 531
53563 673 0 1814 2015-11-05 531
下面是一段代碼,我發現,但適合我的需要。它幾乎解決了我的問題,但我不知道如何從我的第一個記錄中包含範圍日期塊。我知道爲什麼這樣做,但不知道如何正確地解決它:
;With Dates as
(
Select DisbursementID, ServiceProviderID,Original,CircuitID
,Beginning_Service_Date as BeginDate, Ending_Service_Date as EndDate
,Amount From Disbursement
Union All
Select DisbursementID, ServiceProviderID, Original,CircuitID
,DATEADD(day,1,BeginDate) as CalenderDate, EndDate
,Amount
From Dates
Where DATEADD(day,1,BeginDate) <= EndDate
)
Select DisbursementID, ServiceProviderID,Original,CircuitID
,BeginDate as [Date Range], Amount from Dates
Order By CircuitID
Option (MAXRECURSION 366);
謝謝。我沒有一個TALLY/CALENDAR表,我不知道CROSS APPLY是如何工作的,但現在就看看它。 –
哦,我喜歡你編輯過的另一個選項解決方案。使用SQL代碼的我的ETL過程遇到了使用您的第一個解決方案的問題,但是您的EDITED解決方案使其更好。 –
@CharlesBernardes奇怪的是,你有第一個問題。兩人都得到了相同的結果。將CROSS APPLY放在你的後袋裏。他們很有用...把它們當作一個子程序 –