需要查询

时间:2018-10-02 11:00:41

标签: sql-server

table A
Id   Name
---  -----
1     abc
2     bc
3     lm
5     vm
6     ops

Table B
Id    name
---   ------
1     abcd
2     bc
4     hr

我需要一个选择查询,该查询返回如下输出

ID   Name   status
---  ----   -------
1    abcd   Name changed
2    bc     No change
3    lm     Not in table B
4    hr     not in table A
5    vm     not in table B
6    ops    not in table B

1 个答案:

答案 0 :(得分:0)

一个不是很好的解决方案可能是使用CASEFULL JOIN

SELECT 
  CASE WHEN A.name != B.name THEN 'Name changed' ELSE
      CASE WHEN A.name = B.name THEN 'No change' ELSE
          CASE WHEN A.name is null THEN 'Not in table A' ELSE
              CASE WHEN B.name is null THEN 'Not in table B' ELSE
              END
          END
      END
  END status
FROM A
FULL JOIN B ON A.id = B.id