部落纪事: 一条关于求统计分组的最大值的sql

王朝mssql·作者佚名  2006-01-09
宽屏版  字体: |||超大  

日期:2005-6-16

群id:11233046

问题描述:

在上面这个表中,我想要取出相同dept里time1加起来最高的那条记录

如果相同的dept中有两条记录相同则取两个出来

id dept name time1

1 aa x1 3

2 aa x1 4

3 aa x1 5

4 bb x2 4

5 bb x3 5

6 aa x4 7

7 aa x4 5

8 aa x5 3

9 aa x6 4

10 bb x9 3

11 bb x10 10

结果:

dept name sumMax

aa x1 12

aa x4 12

bb x10 10

解答:

//--在access中测试通过

create table tbl

(

id char(10),

dept char(10),

name char(10),

time1 integer

)

insert into tbl(id,dept,name,time1) values('1' ,'aa' ,'x1 ' ,3

)

insert into tbl(id,dept,name,time1) values('2' ,'aa' ,'x1 ' ,4 )

insert into tbl(id,dept,name,time1) values('3' ,'aa' ,'x1 ' ,5)

insert into tbl(id,dept,name,time1) values('4' ,'bb' ,'x2 ' ,4

)

insert into tbl(id,dept,name,time1) values('5' ,'bb' ,'x3 ' ,5)

insert into tbl(id,dept,name,time1) values('6' ,'aa' ,'x4 ' ,7)

insert into tbl(id,dept,name,time1) values('7' ,'aa' ,'x4' ,5

)

insert into tbl(id,dept,name,time1) values('8' ,'aa' ,'x5' ,3 )

insert into tbl(id,dept,name,time1) values('9' ,'aa' ,'x6' ,4 )

insert into tbl(id,dept,name,time1) values('10','bb' ,'x9' ,3 )

insert into tbl(id,dept,name,time1) values('11','bb' ,'x10' ,10)

select dept,name, sum(time1) As sumMax from tbl TmpA

group by dept,name

having ( sum(time1) >= all (select sum(time1) from tbl where TmpA.dept = dept group by name) )

简单评注:

在最初确定功能时候用的是一条比较冗臃拖沓的sql,其中充斥着几个临时表,之后发现其实只是求分组后的结果求最值而已。

于是着手修改。

在having 中进行 比较 是分组后的比较,这样子能够让 比较的次数降低很多,尤其是 纪录数很多 组数很少的情况

在分组的时候的效率已经由数据库保证了。已经是不能更改的。

修改之后的sql果然让人清爽。简单,对称,优美,高效。

实在忍不住将它记下来。

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
© 2005- 王朝网络 版权所有