此处主要是讨论Group by 与 Order by 排序区别。
group by 主要是用于分组聚集,而order by是排序
group by 分组后也是经过排序的,是按照分组条件来进行排序的,可能最终结果并不是我们想要的排序方式。
例
select Cust_Id,count(*) As OrderNum
from orders
where Price >= 10
group by Cust_Id
having count(*) >= 2
结果:
Cust_Id OrderNum
Cid2009 10
Cid2010 8
Cid2011 12
可见其实按照Cust_Id进行排序的
若想要按照 OrderNum排序
则:
select Cust_Id,count(*) As OrderNum
from orders
where Price >= 10
group by Cust_Id
having count(*) >= 2
Order by OrderNum
结果:
Cust_Id OrderNum
Cid2010 8
Cid2009 10
Cid2011 12