我有以下表结构:
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
有什么办法吗?
答案 0 :(得分:0)
您可以使用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
),但这个方法很有趣"。
答案 1 :(得分:0)
我会选择戈登提到的JOIN版本;这样的事情应该保证你提供的确切结果。
SELECT t0.*
FROM t AS t0
INNER JOIN (
SELECT t.CLIENT, MAX(t.TOTAL_EARNED) AS bestEarned
FROM t
GROUP BY t.CLIENT
) AS tBest ON t0.CLIENT= tBest.CLIENT
ORDER BY tBest.bestEarned DESC
, t0.CLIENT ASC
, t0.TOTAL_EARNED DESC
, t0.YEAR
;