在历史日期加入两张桌子

时间:2015-04-21 19:23:23

标签: tsql join sql-server-2012

我有两张桌子。第一个:

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
.
.
.

我要做的是在ColumnOfInterest上的两个表之间建立1:1连接,以便DateOfInterest反映第二个表中的日期。

也就是说,第一个表中的行将连接到第二个表的第三行。

你有什么想法吗?

由于

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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