分组查询出结果集,然后再根据结果集分组查询统计

zbz2188 2007-09-30 09:14:49
我想分组查询出一个结果集,然后再根据结果集分组查询统计
比如有一个表A.字段有id,score,mark,record,dep,它们都是int型
我想以dep分组,每组里,要record最小。最后以record分组统计
数据如下
id score mark record dep
1 1.0 1.0 1 1
2 2.0 2.0 1 2
3 3.0 3.0 1 3
4 2.0 2.0 2 2
5 2.0 2.0 3 2
6 4.0 4.0 2 4
请各位大虾指点,谢谢了
...全文
174 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
zbz2188 2007-09-30
  • 打赏
  • 举报
回复
你以前也回复过我的一个贴子,谢谢你
dawugui 2007-09-30
  • 打赏
  • 举报
回复
create table tb(id int,score int,mark int,record int,dep int)
insert into tb values(1, 1.0, 1.0, 1, 1)
insert into tb values(2, 2.0, 2.0, 1, 2)
insert into tb values(3, 3.0, 3.0, 1, 3)
insert into tb values(4, 2.0, 2.0, 2, 2)
insert into tb values(5, 2.0, 2.0, 3, 2)
insert into tb values(6, 4.0, 4.0, 2, 4)
go

--以dep分组,每组里,要record最小
select a.* from tb a,
(select dep , min(record) record from tb group by dep) b
where a.dep = b.dep and a.record = b.record
/*
id score mark record dep
----------- ----------- ----------- ----------- -----------
1 1 1 1 1
2 2 2 1 2
3 3 3 1 3
6 4 4 2 4
*/

--最后以record分组统计
select record , sum(score) score , sum(mark) mark from
(
select a.* from tb a,
(select dep , min(record) record from tb group by dep) b
where a.dep = b.dep and a.record = b.record
) t
group by record
/*
record score mark
----------- ----------- -----------
1 6 6
2 4 4
*/
drop table tb

zbz2188 2007-09-30
  • 打赏
  • 举报
回复
第二次结果是
score mark record
7.0 6.0 1
4.0 4.0 2

zbz2188 2007-09-30
  • 打赏
  • 举报
回复
第一次查询结果是这样的
id score mark record dep
1 1.0 1.0 1 1
2 3.0 2.0 1 2
3 3.0 3.0 1 3
6 4.0 4.0 2 4
dawugui 2007-09-30
  • 打赏
  • 举报
回复
select record , sum(score) score , sum(mark) mark from
(
select a.* from tb a,
(select dep , min(record) record from tb group by dep) b
where a.dep = b.dep and a.record = b.record
) t
group by record

22,207

社区成员

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

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