在SQL Server中加入表时的条件条件

时间:2019-03-19 18:52:43

标签: sql sql-server tsql join case

我有两个表,分别包含员工数据TableATableB,我基于2个id(其中一个userID和另一个mID(基于月份的ID))使用LEFT OUTER JOIN到大约20%的结果中返回NULL,因为TableB不完整。我想要-如果可能的话,一个查询来检测联接是否找不到匹配项,并将一个月减去到mID中,以便联接可以用旧数据覆盖至少一部分丢失数据。

我不知道这是否是一种过于复杂的查询,但是我想到了类似的东西:

SELECT T1.*, T2.*
FROM TABLEA
LEFT OUTER JOIN TABLEB
ON T2.USERID = T1.USERID AND (CASE WHEN (T2.HID = T1.HID) = NULL THEN (T2.HID = T1.HID-1))

感谢任何帮助。

2 个答案:

答案 0 :(得分:0)

我认为这是您真正想要做的;缺点是逻辑更多,每列都可以重复,但是可以提供很好的控制。

DECLARE @TableA TABLE (USERID INT,HID INT,SomeData VARCHAR(20))
DECLARE @TableB TABLE (USERID INT,HID INT,SomeData VARCHAR(20))

INSERT INTO @TableA(USERID,HID,SomeData) SELECT 1,5,'Now'
INSERT INTO @TableA(USERID,HID,SomeData) SELECT 2,5,NULL
INSERT INTO @TableA(USERID,HID,SomeData) SELECT 3,5,NULL

INSERT INTO @Tableb(USERID,HID,SomeData) SELECT 2,4,'Now-1'
INSERT INTO @Tableb(USERID,HID,SomeData) SELECT 2,3,'Now-2'
INSERT INTO @Tableb(USERID,HID,SomeData) SELECT 3,4,'Now-1'

SELECT
    t1.USERID, T1.Hid AS [Current HID]
    ,
        CASE
            WHEN T1.SomeData IS NOT NULL THEN T1.SomeData
            WHEN T2.USERID IS NOT NULL THEN T2.SomeData
            WHEN T3.USERID IS NOT NULL THEN T3.SomeData
            ELSE T1.SomeData
        END AS [Most Recent SomeData]
FROM @TABLEA T1
LEFT JOIN @TABLEB T2 ON T2.USERID = T1.USERID AND T2.HID = T1.HID
LEFT JOIN @TABLEB T3 ON T3.USERID = T1.USERID AND T3.HID = T1.HID-1

答案 1 :(得分:0)

通过使用case语句,您处在正确的轨道上,但这有点不合时宜。警告!我没有进行测试,但我相信过去也遇到过类似的情况。

SELECT      T1.*
            ,T2.*
FROM        TABLEA  t1
LEFT JOIN   TABLEB  t2  ON      T2.USERID = T1.USERID
                            AND T2.HID =    CASE
                                                WHEN T2.HID = T1.HID then t1.hid
                                                else T1.HID - 1
                                            end