SQL Server:不同日期之间的连接数

时间:2015-02-02 08:32:15

标签: sql-server sql-server-2000

我有2张这样的表:

num   datetime    color
...   ........    .....
40   2007/07/07   red  
40   2012/12/01   white   

name   datetime   num
....   ........   ...
Tom   2008/01/22  40
Tom   2014/02/27  40

我如何在这些表上进行内连接?

name       date     num   color
....   ..........   ...  ......
Tom    2008/01/22   40    red
Tom    2014/02/31   40    white

谢谢!

2 个答案:

答案 0 :(得分:0)

试试这个

;WITH CTE AS
(
    SELECT *,ROW_NUMBER() OVER(ORDER BY (SELECT 0 ))RNO 
    FROM #TABLE1
)
,CTE2 AS
(
    SELECT *,ROW_NUMBER() OVER(ORDER BY (SELECT 0 ))RNO
    FROM #TABLE2
)
SELECT C2.NAME,C2.DATETIME,C2.NUM,C1.COLOR 
FROM CTE C1
JOIN CTE2 C2 ON C1.RNO=C2.RNO and C1.NUM=C2.NUM

对于 SQL SERVER 2000 ,您可以使用以下代码

;WITH CTE AS
(
    SELECT *,(SELECT COUNT(*) FROM #TABLE1 T2 WHERE T1.COLOR<T2.COLOR)RNO 
    FROM #TABLE1 T1
)
,CTE2 AS
(
    SELECT *,(SELECT COUNT(*) FROM #TABLE1 T2 WHERE T1.datetime<T2.datetime)RNO
    FROM #TABLE2 T1
)
SELECT C2.NAME,C2.DATETIME,C2.NUM,C1.COLOR 
FROM CTE C1
JOIN CTE2 C2 ON C1.RNO=C2.RNO and C1.NUM=C2.NUM

答案 1 :(得分:0)

我可以建议您希望第二个表中的所有行和第一个表中的颜色,其中日期小于第二个表并且是最大值。如果是这样的话:

DECLARE @t1 TABLE
    (
      num INT ,
      dt DATETIME ,
      color NVARCHAR(MAX)
    )
DECLARE @t2 TABLE
    (
      num INT ,
      dt DATETIME ,
      name NVARCHAR(MAX)
    )

INSERT  INTO @t1
VALUES  ( 40, '20070707', 'red' ),
        ( 40, '20121201', 'white' )

INSERT  INTO @t2
VALUES  ( 40, '20080122', 'Tom' ),
        ( 40, '20140228', 'Tom' )

SELECT  t2.name ,
        t2.dt ,
        t2.num ,
        c.color
FROM    @t2 t2
        CROSS APPLY ( SELECT TOP 1
                                t1.color
                      FROM      @t1 t1
                      WHERE     t2.num = t1.num
                                AND t1.dt < t2.dt
                      ORDER BY  t1.dt DESC
                    ) c

输出:

name    dt                      num color
Tom     2008-01-22 00:00:00.000 40  red
Tom     2014-02-28 00:00:00.000 40  white