|
日期: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果然让人清爽。简单,对称,优美,高效。 实在忍不住将它记下来。
|