我具有以下表结构:

CLIENT | YEAR | TOTAL_EARNED


带有样本数据:

John  | 2016 | 100
Jane  | 2016 | 50
Joe   | 2016 | 300
John  | 2017 | 200
Jane  | 2017 | 50
Joe   | 2017 | 0


我想按TOTAL_EARNED排序,但也希望将客户记录保持在一起:

Joe   | 2016 | 300
Joe   | 2017 | 0
John  | 2017 | 200
John  | 2016 | 100
Jane  | 2016 | 50
Jane  | 2017 | 50


有什么办法吗?

最佳答案

您可以使用order by中的子查询来做到这一点:

select t.*
from t
order by (select max(t2.total_earned) from t t2 where t2.client = t.client) desc,
         client,
         year


还有其他方法(例如使用join),但是这种方法很有趣。

10-07 19:27
查看更多