我有一个场景,根据另一个表中的Lookup来分割日期。
这里BillDetails和ClientFiscal是源表,BillDetailNormalized是目标表。
对于BillDetailNormalized中的第一条记录,ServiceBeginKey将来自Billdetail Table,即2011-11-09,ServiceEndKey将取决于两个因素:
如果ClientFiscal中没有相应的Enddate,那么它将是月末
否则将是相应的日期 这里来自于它在ClientFiscal表中的共享示例,所以它将是2011-12-10
下一条记录ServiceBeginKey将是2011-12-11,ServiceEndKey将是2011-12-31,因为该月的ClientFiscal表中没有相应的记录
CREATE TABLE BillDetails
(
ClientKey INT,
BillDetailKey INT
,ServiceBeginKey DATETIME
,ServiceEndKey DATETIME
);
INSERT INTO BillDetails VALUES (9,296643,'2011-11-09','2012-01-10');
CREATE TABLE ClientFiscal
(
ClientKey INT,
FiscalBeginKey DATETIME,
FiscalEndKey DATETIME
);
INSERT INTO ClientFiscal VALUES (9,'2011-11-13','2011-12-10');
INSERT INTO ClientFiscal VALUES (9,'2011-12-11','2012-01-07');
INSERT INTO ClientFiscal VALUES (9,'2012-01-08','2012-02-04');
CREATE TABLE BillDetailNormalized
(
BillDetailsNormalizedKey INT,
BillDetailKey INT,
ClientKey INT,
ServiceBeginKey DATETIME,
ServiceEndKey DATETIME
);
INSERT INTO BillDetailNormalized VALUES (443171,296643,9,'2011-12-09','2011-12-10');
INSERT INTO BillDetailNormalized VALUES (443172,296643,9,'2011-12-11','2011-12-31');
INSERT INTO BillDetailNormalized VALUES (443173,296643,9,'2012-01-01','2012-01-07');
INSERT INTO BillDetailNormalized VALUES (443174,296643,9,'2012-01-08','2012-01-10');
答案 0 :(得分:0)
drop table #BillDetails
drop table #ClientFiscal
drop table #BillDetailNormalized
CREATE TABLE #BillDetails
(
ClientKey INT,
BillDetailKey INT
,ServiceBeginKey DATETIME
,ServiceEndKey DATETIME
);
CREATE TABLE #ClientFiscal
(
ClientKey INT,
FiscalBeginKey DATETIME,
FiscalEndKey DATETIME
);
CREATE TABLE #BillDetailNormalized
(
BillDetailsNormalizedKey INT IDENTITY(1,1) NOT NULL,
BillDetailKey INT,
ClientKey INT,
ServiceBeginKey DATETIME,
ServiceEndKey DATETIME
);
INSERT INTO #BillDetails VALUES (9,296643,'2011-11-09','2012-01-10');
INSERT INTO #ClientFiscal VALUES (9,'2011-11-13','2011-12-10');
INSERT INTO #ClientFiscal VALUES (9,'2011-12-11','2012-01-07');
INSERT INTO #ClientFiscal VALUES (9,'2012-01-08','2012-02-04');
INSERT INTO #BillDetailNormalized (BillDetailKey, ClientKey, ServiceBeginKey, ServiceEndKey)
SELECT X.BillDetailKey, X.ClientKey, X.FiscalBeginKey, X.ServiceEndKey
FROM (
SELECT B.BillDetailKey,
C.ClientKey,
C.FiscalBeginKey,
'ServiceEndKey' =
CASE
WHEN B.ServiceEndKey IS NULL THEN DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, B.ServiceEndKey) + 1, 0))
ELSE B.ServiceEndKey
END
FROM #ClientFiscal C
LEFT JOIN #BillDetails B
on C.ClientKey = B.ClientKey
) X
select *
from #ClientFiscal
select *
from #BillDetailNormalized