比较SQL Server表并查找匹配的输出

时间:2019-06-25 20:37:30

标签: sql sql-server tsql

我正在尝试比较两个表AB,以查找存在A但在B中不存在相同记录的实例。

表A:

|PROJECT|ID|USER|DATE|
+-------+--+----+----+
|   2   |1 |ASD |0624|
|   3   |2 |FGH |0624|

表B:

|PROJECT|ID|USER|DATE|
+-------+--+----+----+
|   2   |1 |ASD |0624|

我希望看到这样的输出:

|PROJECT|ID|USER|DATE|MATCHING_ID|
+-------+--+----+----+-----------+
|   2   |1 |ASD |0624|     1     |
|   3   |2 |FGH |0624|    NONE   |

我已经尝试过类似的操作,但是我只是语法或模棱两可的列名错误。我不确定自己在做什么错。我遵循了一些示例,但最终遇到了同样的情况。

SELECT [PROJECT], [ID],  [USER], [DATE]
FROM [TABLE_A] 
LEFT JOIN [TABLE_B] ON [ID] = [ID]
WHERE [DATE] >= DATEADD(mm, -2, GETDATE())

2 个答案:

答案 0 :(得分:1)

修复您的JOIN条件并使用COALESCE()

SELECT A.*, COALESCE(B.ID, 'NONE') as MATCHING_ID
FROM [TABLE_A] A LEFT JOIN
     [TABLE_B] B
     ON A.[ID] = B.[ID] AND
        A.[DATE] = B.[DATE] AND
        A.PROJECT = B.PROJECT AND
        A.USER = B.USER;

答案 1 :(得分:0)

您可以使用CASE语句和EXISTS:

SELECT a.*,
CASE WHEN EXISTS (
  SELECT 1 FROM [TABLE_B] b
  WHERE a.PROJECT = b.PROJECT AND a.ID = b.ID AND a.USER = b.USER AND a.DATE = b.DATE
) THEN a.ID ELSE 'NONE' END MATCHING_ID
FROM [TABLE_A] a