group by分组查询实例
group by实例
实例一
数据表:
姓名 科目 分数
张三 语文 80
张三 数学 98
张三 英语 65
李四 语文 70
李四 数学 80
李四 英语 90
期望查询结果:
姓名 语文 数学 英语
张三 80 98 65
李四 70 80 90
代码
create table testScore
(
tid int primary key identity(1,1),
tname varchar(30) null,
ttype varchar(10) null,
tscor int null
)
go
---插入数据
insert into testScore values ('张三','语文',80)
insert into testScore values ('张三','数学',98)
insert into testScore values ('张三','英语',65)
insert into testScore values ('李四','语文',70)
insert into testScore values ('李四','数学',80)
insert into testScore values ('李四','英语',90)
select tname as '姓名' ,
max(case ttype when '语文' then tscor else 0 end) '语文',
max(case ttype when '数学' then tscor else 0 end) '数学',
max(case ttype when '英语' then tscor else 0 end) '英语'
from testScore
group by tname
实例二
有如下数据
国家(country) 性别(sex) 人口(population)
中国 1 340
中国 2 260
美国 1 45
美国 2 55
加拿大 1 51
加拿大 2 49
英国 1 40
英国 2 60
按照国家和性别进行分组,得出结果如下
国家 男 女
中国 340 260
美国 45 55
加拿大 51 49
英国 40 60
代码
SELECT country,
SUM( CASE WHEN sex = '1' THEN
population ELSE 0 END), --男性人口
SUM( CASE WHEN sex = '2' THEN
population ELSE 0 END) --女性人口
FROM Table_A
GROUP BY country;
参考资料: SQL group by分组查询 http://www.studyofnet.com/news/247.html
实例一
数据表:
姓名 科目 分数
张三 语文 80
张三 数学 98
张三 英语 65
李四 语文 70
李四 数学 80
李四 英语 90
期望查询结果:
姓名 语文 数学 英语
张三 80 98 65
李四 70 80 90
代码
create table testScore
(
tid int primary key identity(1,1),
tname varchar(30) null,
ttype varchar(10) null,
tscor int null
)
go
---插入数据
insert into testScore values ('张三','语文',80)
insert into testScore values ('张三','数学',98)
insert into testScore values ('张三','英语',65)
insert into testScore values ('李四','语文',70)
insert into testScore values ('李四','数学',80)
insert into testScore values ('李四','英语',90)
select tname as '姓名' ,
max(case ttype when '语文' then tscor else 0 end) '语文',
max(case ttype when '数学' then tscor else 0 end) '数学',
max(case ttype when '英语' then tscor else 0 end) '英语'
from testScore
group by tname
实例二
有如下数据
国家(country) 性别(sex) 人口(population)
中国 1 340
中国 2 260
美国 1 45
美国 2 55
加拿大 1 51
加拿大 2 49
英国 1 40
英国 2 60
按照国家和性别进行分组,得出结果如下
国家 男 女
中国 340 260
美国 45 55
加拿大 51 49
英国 40 60
代码
SELECT country,
SUM( CASE WHEN sex = '1' THEN
population ELSE 0 END), --男性人口
SUM( CASE WHEN sex = '2' THEN
population ELSE 0 END) --女性人口
FROM Table_A
GROUP BY country;
参考资料: SQL group by分组查询 http://www.studyofnet.com/news/247.html
> 我来回应
热门话题 · · · · · · ( 去话题广场 )
- 锦绣芳华追剧手记592篇内容 · 47.9万次浏览
- 想做的事,别等“以后”1.0万+篇内容 · 771.9万次浏览
- 夏日限定的绿色美学1316篇内容 · 47.1万次浏览
- 抬头看看,这个刚诞生的夏天422篇内容 · 70.3万次浏览
- 重新养一遍自己,可真好啊3317篇内容 · 501.5万次浏览
- 中年人感悟特别多1598篇内容 · 754.2万次浏览
- 哪个瞬间你发现自己被琐碎地爱着?791篇内容 · 177.7万次浏览
- 你有哪些“终不似,少年游”的经历?3690篇内容 · 139.9万次浏览