关于group by 的问题 急!在线等答案

bsl6030 2008-10-17 02:43:49
表是这样的 表名student
pid //学号
pname //姓名
sex //性别 只有三种 W女 m男 u未知
birthday //生日
cid //专业

想查询出这样的结果
专业 男生人数 女生人数 未知性别人数 总人数

我知道如果不要求统计男女生人数 就可以这样解决
select cid,count(sex)from student group by cid

结果是
cid count(sex)
1 3
2 3
3 2
4 1
但是要加入性别的列 就不知道这么弄了 表中本来就没这几列

哪位前辈指点指点!
我新来的没分给 不好意思啊 以后加倍给
...全文
83 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
bsl6030 2008-10-17
  • 打赏
  • 举报
回复
原来sum()里可以这样用啊 还不知道呢 真是收益非浅啊!
非常感谢!
bsl6030 2008-10-17
  • 打赏
  • 举报
回复
原来sum()里可以这样用啊 还不知道呢 真是收益非浅啊!
非常感谢!
lp370480 2008-10-17
  • 打赏
  • 举报
回复
select cid as 专业,
count(*)as 总人数,
sum( case when sex = 'm' then 1 else 0 end)as男人,
sum(case when sex = 'w' then 1 else 0 end)as 女人,
sum(case when sex = 'u' then 1 else 0 end)as 未知性别人
from student
group by cid

yueqing 2008-10-17
  • 打赏
  • 举报
回复
人妖 强
yygyogfny 2008-10-17
  • 打赏
  • 举报
回复
专业 总人数 男人 女人 人妖
----------- ----------- ----------- ----------- -----------
1 1 0 1 0
2 5 2 1 2
3 1 1 0 0

(3 row(s) affected)
yygyogfny 2008-10-17
  • 打赏
  • 举报
回复
刚忘了一列了:

再来:
select cid as 专业,
总人数 = count(*),
男人 = sum( case when sex = 'm' then 1 else 0 end),
女人 = sum(case when sex = 'w' then 1 else 0 end),
人妖 = sum(case when sex='u' then 1 else 0 end)
from student
group by cid
yygyogfny 2008-10-17
  • 打赏
  • 举报
回复

create table student
(pid int,
pname nvarchar(20),
sex char(2),
birthday datetime,
cid int
)
insert into student
select 1,'a','w',getdate(),1
union all
select 2,'b','w',getdate(),2
union all
select 3,'c','m',getdate(),3
union all
select 4,'d','u',getdate(),2
union all
select 4,'e','u',getdate(),2
union all
select 4,'f','m',getdate(),2
union all
select 4,'g','m',getdate(),2

select * from student

select cid as 专业,
总人数 = count(*),
男人 = sum( case when sex = 'm' then 1 else 0 end),
女人 = sum(case when sex = 'w' then 1 else 0 end)
from student
group by cid


专业 总人数 男人 女人
----------- ----------- ----------- -----------
1 1 0 1
2 5 2 1
3 1 1 0

(3 row(s) affected)

34,590

社区成员

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

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