2012-03-01 68 views
0

SQL問題,可能不是最困難的。通過t1.date加入不相關的表(在t2.startdate和t2.enddate之間)

我正在從一堆相關表連接的ID's - > easy進行查看。現在有一張桌子與其他所有人沒有關係。 (BatchDates)

`ALTER VIEW [ECSUB].[FCT_Ext_Collection] 
AS 
SELECT  sh.id AS idSubmissionHistory, dh.id, dd.id AS Description, sch.id AS idScoringHistory, sh.CreationDate, sh.UpdateDate, bd.id AS BatchDateID 
FROM   ECSUB.SubmissionHistory AS sh INNER JOIN EC.DocumentHistory AS dh ON sh.id = dh.idSubmissionHistory 
         LEFT OUTER JOIN ECSM.ScoringHistory AS sch ON sh.idScoringHistory = sch.id 
         LEFT OUTER JOIN EC.DocumentDescriptions AS dd ON dd.id = dh.Description 
         LEFT OUTER JOIN ECSUB.AddressBilling AS ab ON sh.id = ab.id 
         LEFT OUTER JOIN ECSUB.AddressPremise AS ap ON sh.id = ap.id 
         CROSS JOIN EC.BatchDates AS bd --ON sh.documentdate between ....... 

GO` 

好了,我的主表「documentHistory」包含文件的日期,我必須定義在該批次下降。 每批有一個ID和startdate。一批總是一個月。

這將使它更容易理解,從BatchDates表中的數據:

id month startdate 
1 2010-12-01 00:00:00.000 2010-12-01 00:00:00.000 
1 2011-01-01 00:00:00.000 2010-12-01 00:00:00.000 
1 2011-02-01 00:00:00.000 2010-12-01 00:00:00.000 
2 2011-03-01 00:00:00.000 2011-03-01 00:00:00.000 
2 2011-04-01 00:00:00.000 2011-03-01 00:00:00.000 
2 2011-05-01 00:00:00.000 2011-03-01 00:00:00.000 
3 2011-06-01 00:00:00.000 2011-06-01 00:00:00.000 
3 2011-07-01 00:00:00.000 2011-06-01 00:00:00.000 
3 2011-08-01 00:00:00.000 2011-06-01 00:00:00.000 
4 2011-09-01 00:00:00.000 2011-09-01 00:00:00.000 
4 2011-10-01 00:00:00.000 2011-09-01 00:00:00.000 
4 2011-11-01 00:00:00.000 2011-09-01 00:00:00.000 
5 2011-12-01 00:00:00.000 2011-12-01 00:00:00.000 
5 2012-01-01 00:00:00.000 2011-12-01 00:00:00.000 
5 2012-02-01 00:00:00.000 2011-12-01 00:00:00.000 
6 2012-03-01 00:00:00.000 2012-03-01 00:00:00.000 
6 2012-04-01 00:00:00.000 2012-03-01 00:00:00.000 
6 2012-05-01 00:00:00.000 2012-03-01 00:00:00.000 
7 2012-06-01 00:00:00.000 2012-06-01 00:00:00.000 
7 2012-07-01 00:00:00.000 2012-06-01 00:00:00.000 
7 2012-08-01 00:00:00.000 2012-06-01 00:00:00.000 
8 2012-09-01 00:00:00.000 2012-09-01 00:00:00.000 
8 2012-10-01 00:00:00.000 2012-09-01 00:00:00.000 
8 2012-11-01 00:00:00.000 2012-09-01 00:00:00.000 
9 2012-12-01 00:00:00.000 2012-12-01 00:00:00.000 
9 2013-01-01 00:00:00.000 2012-12-01 00:00:00.000 
9 2013-02-01 00:00:00.000 2012-12-01 00:00:00.000 
10 2013-03-01 00:00:00.000 2013-03-01 00:00:00.000 
10 2013-04-01 00:00:00.000 2013-03-01 00:00:00.000 
10 2013-05-01 00:00:00.000 2013-03-01 00:00:00.000 
etc........... 

所以我需要根據documentdate去取batchID,因此我們使用的列currentMonth開始日期。

這樣:... JOIN BatchDates其中documentDate是startDate.month(沒有此之間)

我甚至不知道我是否需要一個連接,交叉連接,工會等...

在此先感謝! L

回答

1
join BatchDates 
on datepart(yyyy,[document date]) = datepart(yyyy,[startDate]) 
and datepart(mm,[document date]) = datepart(mm,[startDate]) 
+0

看起來不錯!我會嘗試並在此報告。謝謝!! – laurens 2012-03-01 22:43:35

+0

好吧,這個作品魅力...還有內/外連接。謝謝 ! – laurens 2012-03-02 12:59:56

相關問題