恳求SQL语句
表A:
id
a
b
c
d
表B:
id
a
c
a
c
a
结果:
a 1
b 0
c 1
d 0
要求:存储过程中处理,可多步,但不能用游标,即不能单笔循环处理
逻辑:对于A表中的id,如果存在于B表中(不论多少),则数量标记为1,否则为0
还请不吝赐教,谢谢
------解决方案--------------------select a,case when exists(select 1 from b where b.id = a.id) then 1 else 0
end as count
from a
------解决方案----------------------建立測試環境
Create Table A
(id Varchar(10))
Insert A Select 'a '
Union All Select 'b '
Union All Select 'c '
Union All Select 'd '
Create Table B
(id Varchar(10))
Insert B Select 'a '
Union All Select 'c '
Union All Select 'a '
Union All Select 'c '
Union All Select 'a '
GO
--測試
Select
A.id,
(Case When B.id Is Not Null Then 1 Else 0 End) As 标记
From
A
Left Join
(Select Distinct id From B) B
On A.id = B.id
GO
--刪除測試環境
Drop Table A, B
--結果
/*
id 标记
a 1
b 0
c 1
d 0
*/