我有表A和表B。我必须使用以下格式比较这2个表的记录并使用SQL Server过程返回数据。
表A
id name description
1 A desc A
2 B desc B
3 C desc C
4 D desc D
5 E desc E
6 F desc F
7 G desc G
8 H desc H
9 I desc I
10 J desc J
表B
id name description
1 A desc A
2 B desc B
3 M desc M
4 N desc N
5 O desc O
6 C desc C
7 D desc D
8 E desc E
9 G desc G
10 H desc H
11 I desc I
12 J desc J
期望的输出如下。它有一个额外的字段“状态”,以提及已添加或删除的记录。
name description status
A desc A
B desc B
M desc M newly added
N desc N newly added
O desc O newly added
C desc C
D desc D
E desc E
F desc F removed
G desc G
H desc H
I desc I
J desc J
我尝试过如下代码
select
coalesce(a.name, b.name) name,
coalesce(a.description, b.description) description,
case
when a.name is null then 'newly added'
when b.name is null then 'removed'
end status
from tablea a
full join tableb b on b.name = a.name
但是在输出中,新添加的记录M,N,O位于最后一个位置。M,N,O应该在B下,如输入表中所示。我没有按预期输出中的顺序获得输出。
您去这里
with t as (select
coalesce(a.name, b.name) name,
coalesce(a.description, b.description) description,
case
when a.name is null then 'newly added'
when b.name is null then 'removed'
end status,
case
when a.id is null then b.id else a.id
end id
from table1 a
full join table2 b on b.name = a.name)
select name,description,status from t order by id