在SQL Server 2016中,我有这两个表:
表A:
ID Description
X Desc1
Y Desc2
Z Desc3
表B:
Name F_ID F_Description
A X Desc1
A Y Desc2
B X Desc1
C Y Desc2
C Z Desc3
D Z Desc3
我应该使用IfExist列(布尔)列返回所有数据。
我的预期输出是:
Name F_ID F_Description IfExist
A X Desc1 1
A Y Desc2 1
A Z Desc3 0
B X Desc1 1
B Y Desc2 0
B Z Desc3 0
C X Desc1 0
C Y Desc2 1
C Z Desc3 1
D X Desc1 0
D Y Desc2 0
D Z Desc3 1
我该如何管理?
答案 0 :(得分:1)
我认为您需要:
SELECT b.Name
, a.F_ID
, a.F_Description
, CASE WHEN b2.ID IS NULL THEN 0 ELSE 1 END AS IfExists
FROM (
SELECT DISTINCT Name
FROM tableB
) b
CROSS JOIN tableA a
LEFT JOIN tableB b2 ON b.Name = b2.Name AND a.ID = b2.F_ID