求一个group by 句子

guy1218 2007-02-03 04:54:27
表大致如下:

Gender Section
M 1
M 1
F 1
F 2
M 2
M 1
M 2
F 3
M 2
M 3
F 3
....

我用

select section, count(*) as MaleNum from table
group by section
having Gender = 'M'

求每个班的男生数量,可是好像不行,语法错误。我又想不出哪里错了。。
帮帮忙吧!
...全文
256 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
guy1218 2007-02-06
  • 打赏
  • 举报
回复
嗯,可以了。谢谢啦!
marco08 2007-02-03
  • 打赏
  • 举报
回复
create table T(Gender char(1), [Section] int)
insert T select 'M', 1
union all select 'M', 1
union all select 'F', 1
union all select 'F', 2
union all select 'M', 2
union all select 'M', 1
union all select 'M', 2
union all select 'F', 3
union all select 'M', 2
union all select 'M', 3
union all select 'F', 3
union all select 'F', 4 --新加的记录

select distinct [Section],
MaleNum=(select count(*) from T where [Section]=tmp.[Section] and Gender='M')
from T as tmp

--result
Section MaleNum
----------- -----------
1 3
2 3
3 1
4 0

(4 row(s) affected)
guy1218 2007-02-03
  • 打赏
  • 举报
回复
问题是如果某个section没有男生,那你这个就不会返回任何结果。我要的结果是0。
zsl5305256 2007-02-03
  • 打赏
  • 举报
回复
select section, count(*) as MaleNum from table
where Gender = 'M'
group by section
marco08 2007-02-03
  • 打赏
  • 举报
回复
create table T(Gender char(1), [Section] int)
insert T select 'M', 1
union all select 'M', 1
union all select 'F', 1
union all select 'F', 2
union all select 'M', 2
union all select 'M', 1
union all select 'M', 2
union all select 'F', 3
union all select 'M', 2
union all select 'M', 3
union all select 'F', 3

select section, count(*) as MaleNum from T
where Gender = 'M'
group by section

--result
section MaleNum
----------- -----------
1 3
2 3
3 1

(3 row(s) affected)
marco08 2007-02-03
  • 打赏
  • 举报
回复
select section, count(*) as MaleNum from table
where Gender = 'M'
group by section

22,207

社区成员

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

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