求救! 一个sql语句,请高手指点.

来源:百度知道 编辑:UC知道 时间:2024/05/15 08:23:53
我现在有a,b两个表,他们都有字段sjh,b表还有字段schoolid,我想计算a表中有b表中的sjh的个数并且以b表中的schoolid分组.
我用如下sql语句:
select count(*),b.schoolid from a,b where a.sjh=b.sjh group by b.schoolid
可是如果,a表中没有b表中的sjh时,计算结果应该为0.
但是由于a.sjh=b.sjh 不成立,所以不会有计算结果.我想要计算结果为0,也显示出来怎么办,请高手指点,谢谢!

select count(a.sjh),b.schoolid from a right join b on a.sjh=b.sjh group by b.schoolid

这样试试...把握不大!!

text44是对的,其他两个是错的
declare @a table (sjh int)
declare @b table (sjh int,schoolid int)
insert into @a(sjh)
select 1
union all select 2
union all select 3
union all select 4
union all select 6

insert into @b(sjh,schoolid)
select 1,2
union all select 2,2
union all select 3,3
union all select 4,3
union all select 5,4

select schoolid,count(a.sjh) as num from @b b left join @a a on a.sjh=b.sjh group by schoolid

--结果

schoolid num
----------- -----------
2 2
3 2
4 0

你可以先用join把两个表连起来

select count(*),b.schoolid from a left join b on a.sjh=b.sjh group by b.schoolid

select count(b.sjh) from b where sjh in (select a.sjh from a ) group by b.schoolid