日期:2014-05-18  浏览次数:20613 次

非 GROUP BY 分组字段 排序问题
非 GROUP BY 分组字段 排序问题

tabaleA
ID F2 F3
1 a 10
2 a 10
3 b 20
4 b 20

select [f2],f3=sum(f3) from tableA group by [f2] 
得出以f2排序的列表。
现想以id排序怎么办?



------解决方案--------------------
select [f2],f3=sum(f3) from tableA group by [f2] order by min(id) -- max(id)
------解决方案--------------------
假设
tabaleA 
ID F2 F3 
1 a 10 
2 b 10 
3 b 20 
4 a 20 

那么group by f2 后
f2 sumF3
a 30
b 30

a的id有1,4
b的id有2,3
你要按id排,那么是a排前面还是b排前面? 也即, 是a取1,还是4,对应b取2还是3的问题.

只有用聚合.

别的不多说了.

如果不理解,就去读下二维关系的定义吧.

------解决方案--------------------
select 
[f2],
f3=sum(f3) 
from 
tableA t
group by [f2]
order by(select max(ID) from tableA where f2=t.t2) desc--以最小的那个ID为条件

------解决方案--------------------
SQL code

select [f2],f3=sum(f3) from tableA group by [f2] having ordey by id

------解决方案--------------------
我的错了,要取一组都是最大的或者都是最小的id
SQL code

select [f2],f3=sum(f3),(select max(ID) from tableA where f2=t.t2) as id from tableA group by [f2] having ordey by id