Sql 比较不同表中的行
我在SQL SERVER中有表A和表B。我想比较每个表中一行的一些列,并从表a返回不同的值。 我该怎么做 例如:Sql 比较不同表中的行,sql,sql-server,tsql,Sql,Sql Server,Tsql,我在SQL SERVER中有表A和表B。我想比较每个表中一行的一些列,并从表a返回不同的值。 我该怎么做 例如: TABLE A columns : id txt1 txt2 txt3 values : 1 XY XX XXY TABLE B columns : id txt1 txt2 txt3 txt4 values : 1 XZ XX XYZ XXX 我想要结果: TABLE A txt1 txt3 XY
TABLE A
columns : id txt1 txt2 txt3
values : 1 XY XX XXY
TABLE B
columns : id txt1 txt2 txt3 txt4
values : 1 XZ XX XYZ XXX
我想要结果:
TABLE A
txt1 txt3
XY XXY
这篇评论太长了 SQL查询返回一组固定的列。所以,你不能做你想做的事。动态SQL甚至不起作用,因为不同的行可能有不同的列集 您可以执行类似于
NULL
的操作,输出相同的值:
select a.id,
nullif(a.txt1, b.txt1) as txt1,
nullif(a.txt2, b.txt2) as txt2,
nullif(a.txt3, b.txt3) as txt3,
nullif(a.txt4, b.txt4) as txt4
from a left join
b
on a.id = b.id;
或列出不同列的名称:
select a.id,
concat_ws(',',
(case when a.txt1 = b.txt1 then 'txt1' end),
(case when a.txt2 = b.txt2 then 'txt2' end),
(case when a.txt3 = b.txt3 then 'txt3' end),
(case when a.txt4 = b.txt4 then 'txt4' end)
)
from a left join
b
on a.id = b.id;