2015-04-21 51 views
-2

我有兩張表。第一招:加入歷史日期的兩張表

col1 | col2 | ColumnOfInterest | DateOfInterest 
-------------------------------------------------------- 
abc | def |  ghi  | 2013-02-24 17:48:32.548 
. 
. 
. 

第二個:

ColumnOfInterest | DateChanged    | col3 | col4 
-------------------------------------------------------- 
     ghi  | 2012-08-13 06:28:11.092 | jkl | mno 
     ghi  | 2012-10-16 23:54:07.613 | pqr | stu 
     ghi  | 2013-01-29 14:13:18.502 | vwx | yz1 
     ghi  | 2013-10-01 14:17:32.992 | 234 | 567 
. 
. 
. 

我試圖做的是做一個1:1的ColumnOfInterest並使得DateOfInterest反映了這兩個表之間的連接第二張表格的日期。

也就是說,第一個表中的行將被連接到第二個表的第三行。

你有什麼想法嗎?

感謝

+1

所以你試圖讓從DateChanged列最大日期爲每個不同的ColumnOfInterest? – hines

+0

嗯,不是最大日期......因爲你可以看到第二個表是一種歷史表,所以我需要一個與第一個表的DateOfInterest相關的行......希望它有意義 –

+0

什麼是你的期望的輸出? – Stephan

回答

1
select table1.ColumnOfInterest, max(table2.DateChanged) 
    from table1 
    join table2 
    on table1.ColumnOfInterest = table1.ColumnOfInterest 
    and table1.CDateOfInterest >= table2.DateChanged 
group by table1.ColumnOfInterest 
0
SELECT 'abc' col1, 
     'def' col2, 
     'ghi' ColumnOfInterest, 
     CAST('2013-02-24 17:48:32.548' AS DATETIME) DateOfInterest 
INTO #DateOfInterest 


CREATE TABLE #History 
(
ColumnOfInterest VARCHAR(5), 
DateChanged DATETIME, 
col3 VARCHAR(5), 
col4 VARCHAR(5) 
) 
INSERT INTO #History 
VALUES ('ghi','2012-08-13 06:28:11.092','jkl','mno'), 
     ('ghi','2012-10-16 23:54:07.613','pqr','stu'), 
     ('ghi','2013-01-29 14:13:18.502','vwx','yz1'), 
     ('ghi','2013-10-01 14:17:32.992','234','567'); 

;WITH CTE_Date_Ranges 
AS 
(
SELECT ColumnOfInterest, 
     DateChanged, 
     LAG(DateChanged,1,GETDATE()) OVER (PARTITION BY ColumnOfInterest ORDER BY DateChanged) AS end_date, 
     col3, 
     col4 
FROM #History 
) 

SELECT B.*, 
     A.* 
FROM CTE_Date_Ranges A 
INNER JOIN #DateOfInterest B 
ON B.DateOfInterest > A.DateChanged AND B.DateOfInterest < A.end_date 

結果:

col1 col2 ColumnOfInterest DateOfInterest   ColumnOfInterest DateChanged    end_date    col3 col4 
---- ---- ---------------- ----------------------- ---------------- ----------------------- ----------------------- ----- ----- 
abc def ghi    2013-02-24 17:48:32.547 ghi    2012-08-13 06:28:11.093 2015-04-21 18:46:46.967 jkl mno