求sql统计最优方法

anticlimax 2006-02-10 05:00:43
表a
行业ID 行业名称
11 农业
12 工业
13 服务业
14 林业

表b
商机ID 行业ID
1 11
2 11
3 12
4 13
5 12
6 11

要求得到

行业ID 行业名称 商机数目
11 农业 3
12 工业 2
13 服务业 1
14 林业 0


我是这样写得
select a.行业ID,a.行业名称,(case when c.thenum is Null then 0 else c.thenum end) as 商机数目 from a full join (select 行业ID,count(*) as thenum from b group by 行业ID) c on a.行业ID=c.行业ID
实际上是先从表b中进行分组统计再与表a匹配

觉得应该有另一种方法根据表a得行业ID对表b进行count(*)统计,效率似乎要高些,哪位写出来,讨论一下
...全文
75 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
anticlimax 2006-02-10
  • 打赏
  • 举报
回复
倒,更简洁的方法,汗
select a.行业ID ,a.行业名称,(select count(*) from b where 行业ID =a.行业ID ) as 商机数目 from a
$扫地僧$ 2006-02-10
  • 打赏
  • 举报
回复
declare @表a table(行业ID int ,行业名称 varchar(20))
insert into @表a select 11,'农业'
union all select 12,'工业'
union all select 13,'服务业'
union all select 14,'林业'

declare @表b table(商机ID int ,行业ID int)
insert into @表b select 1,11
union all select 2,11
union all select 3,12
union all select 4,13
union all select 5,12
union all select 6,11


select A.行业ID,A.行业名称,(select count(1) from @表b where 行业ID=A.行业ID) as 商机数目
from @表a A
anticlimax 2006-02-10
  • 打赏
  • 举报
回复
倒,更简洁的方法,汗
select a.行业ID ,a.行业名称,(select count(*) from b where 行业ID =a.行业ID ) as 商机数目 from a
zlp321002 2006-02-10
  • 打赏
  • 举报
回复
--测试环境
declare @表a table(行业ID int ,行业名称 varchar(20))
insert into @表a select 11,'农业'
union all select 12,'工业'
union all select 13,'服务业'
union all select 14,'林业'

declare @表b table(商机ID int ,行业ID int)
insert into @表b select 1,11
union all select 2,11
union all select 3,12
union all select 4,13
union all select 5,12
union all select 6,11

--查询
Select
行业ID=A.行业ID,
行业名称=A.行业名称,
商机数目=count(B.行业ID)
from @表a A left join @表b B
on A.行业ID=B.行业ID
Group by A.行业ID,A.行业名称
Order by count(B.行业ID) desc
--结果
/*
行业ID 行业名称 商机数目
----------- -------------------- -----------
11 农业 3
12 工业 2
13 服务业 1
14 林业 0

(所影响的行数为 4 行)
*/
lsqkeke 2006-02-10
  • 打赏
  • 举报
回复
用left join 表b无记录时 为null 不为0


select a.行业ID,
a.行业名称,
商机数目=(select count(1) from 表b where 行业ID=a.行业ID group by 行业ID)
from 表a
union
select a.行业ID,
a.行业名称,
商机数目=0
from 表a
where 表a.行业ID not in(select distinct 行业ID from 表b )
zlp321002 2006-02-10
  • 打赏
  • 举报
回复
Select
行业ID=A.行业ID,
行业名称=A.行业名称,
商机数目=count(B.行业ID)
from 表a A left join 表b B
on A.行业ID=B.行业ID
Group by A.行业ID,A.行业名称

34,587

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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