22,209
社区成员
发帖
与我相关
我的任务
分享
if object_id('Tempdb..#a') is not null drop table #a
if object_id('Tempdb..#b') is not null drop table #b
create table #a(
[id] int identity(1,1) not null,
[name] nvarchar(100) null
)
create table #b(
[id] int identity(1,1) not null,
[a_id] int null
)
--a表插入6条记录
Insert Into #a
select 'name1' union all
select 'name2' union all
select 'name3' union all
select 'name4' union all
select 'name5' union all
select 'name6'
--b表插入5条记录
Insert Into #b
select 1 union all
select 2 union all
select 3 union all
select 4 union all
select 5
--查询
select count(1) as 总记录,sum(case when a.id=b.a_id then 1 else 0 end) as 安装b记录数
from #a a left join #b b on a.id=b.a_id
-------------
(6 行受影响)
(5 行受影响)
总记录 安装b记录数
----------- -----------
6 5
(1 行受影响)
/*
总记录 安装记录数
2 1
*/
;with a(id,name) as
(
select 1,'name1'
union all select 2,'name2'
),
b(id,a_id) as
(
select 1,1
)
select COUNT(*) as 总记录,(select COUNT(b.a_id) from b inner join a on a.id=b.a_id) 安装记录数
from a
select COUNT(*) as 总记录,(select COUNT(*) from b where a.id=b.a_id) as 安装记录数
from a