读书人

group by 分组有关问题

发布时间: 2012-12-27 10:17:10 作者: rapoo

group by 分组问题

select title,count(Title),count(TutorType),COUNT(Degree) from TeamInfo group by Title

比如我有一个TeamInfo 表 表数据为
id name title tutortype degree
1 张三 教授 博导 博士
2 李四 副教授 硕导 硕士
3 张四 讲师 硕导 博士
4 张五 讲师 硕士
5 张六 教授 博导 博士
6 张七 讲师 硕导 博士

现在我想统计出下面的形式,分别统计出职称的数据。
职称 人数 博导 硕导 博士学位 硕士学位
教授 2 2 0 2 0
副教授 1 0 1 0 1
讲师 3 0 2 2 1

我上面的命令执行之后统计出来的数据都是一样的。我该怎么改啊
[最优解释]
select title 职称,COUNT(1) 人数,
sum(case when tutortype='博导' then 1 else 0 end) as 博导,
sum(case when tutortype='硕导' then 1 else 0 end) as 硕导,
sum(case when degree='博士' then 1 else 0 end) as 博士,
sum(case when degree='硕士' then 1 else 0 end) as 硕士
from teaminfo
group by title
[其他解释]
跟行列转换差不多啊
可以动态生成sql
楼主看看从这里能不能受到启发

我也是摘自网络

1.--行列转换

原表:?? 姓名???? 科目?? 成绩
?????????? 张三?????语文????80
???????????张三???? 数学??? 90
????????? ?张三???? 物理??? 85
???????? ? 李四?????语文??? 85
?????????? 李四?????物理??? 82
????????? ?李四?????英语??? 90
???????????李四?????政治??? 70
????????? ?王五?????英语??? 90
转换后的表:? 姓名?????? 数学??? 物理???? 英语??? 语文??? 政治?
?????????????????????? 李四?????????0?????????82????????90??????85???????70
???????? ????????????? 王五???????? 0??????????0?????????90?????? 0???????? 0
????????? ???????????? 张三??????? 90??????? 85?????????0?????? 80??????? 0


实例:
create table cj? --创建表cj
(
??? ID?????? Int IDENTITY (1,1)???? not null, --创建列ID,并且每次新增一条记录就会加1
??? Name???? Varchar(50),???
??? Subject? Varchar(50),
??? Result?? Int,??
??? primary key (ID)????? --定义ID为表cj的主键??????
);
--Truncate table cj
--Select * from cj
Insert into cj
Select '张三','语文',80 union all?
Select '张三','数学',90 union all
Select '张三','物理',85 union all
Select '李四','语文',85 union all
Select '李四','物理',82 union all
Select '李四','英语',90 union all
Select '李四','政治',70 union all
Select '王五','英语',90
--行列转换
Declare @sql varchar(8000)
Set @sql = 'Select Name as 姓名'
Select @sql = @sql + ',sum(case Subject when '''+Subject+''' then Result else 0 end) ['+Subject+']'
from (select distinct Subject from cj) as cj? --把所有唯一的科目的名称都列举出来
Select @sql = @sql+' from cj group by name'
Exec (@sql)


[其他解释]
那就动态组成语句吧,也不难。
[其他解释]
引用:
select title 职称,COUNT(1) 人数,
sum(case when tutortype='博导' then 1 else 0 end) as 博导,
sum(case when tutortype='硕导' then 1 else 0 end) as 硕导,
sum(case when degree='博士' then 1 else 0 end) as 博士,
sum(c……

tutortype='博导' 这句不规定不行么,因为类似博导这种数据我很能动态添加别的数据,没有自动的方法么


[其他解释]
谢谢,我再看看还没好的方法,

读书人网 >SQL Server

热点推荐