求一SQL语句 急!!!!

少数派007 2013-09-12 01:59:52
a表:id,name
b表:id,a_id(外键)
我现在要查a表中安装了b的记录数

比如a表记录
1,name1
2, name2
b表记录
1,1
那我要查的总记录数为2,安装了b的记录数为1

必须一条SQL语句搞定, 谢谢了
...全文
86 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
IEEE_China 2013-09-12
  • 打赏
  • 举报
回复


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 行受影响)

Andy__Huang 2013-09-12
  • 打赏
  • 举报
回复
/*
总记录	安装记录数
2	1
*/
Andy__Huang 2013-09-12
  • 打赏
  • 举报
回复
;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
yiyishuitian 2013-09-12
  • 打赏
  • 举报
回复
select count(A.ID) from A join B on A.ID = B.a_id 是不是这意思
引用 楼主 iverson1983 的回复:
a表:id,name b表:id,a_id(外键) 我现在要查a表中安装了b的记录数 比如a表记录 1,name1 2, name2 b表记录 1,1 那我要查的总记录数为2,安装了b的记录数为1 必须一条SQL语句搞定, 谢谢了
Andy__Huang 2013-09-12
  • 打赏
  • 举报
回复
select COUNT(*) as 总记录,(select COUNT(*) from b where a.id=b.a_id) as 安装记录数
from a

22,209

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧