如何使用特定条件的最高值对列表进行排序?

时间:2014-03-31 07:37:14

标签: mysql sql

对于表格中的以下数据,我希望获得每个人的最高余额,然后按照该最高余额的降序对结果进行排序:

|---------id--------|--------name--------|--------balance--------

          1         |        Tom         |      10
          2         |        Bob         |      20
          3         |        Ace         |      60
          4         |        Tom         |      45
          5         |        Ace         |      35
          6         |        Tom         |      75
          7         |        Dan         |      15
          8         |        Dan         |      95
          9         |        Tom         |      40
          10        |        Dan         |      30
          11        |        Bob         |      65
          12        |        Dan         |      55
          13        |        Bob         |      50

预期结果是(按降序排列):

|--------id---------|--------name--------|--------balance--------

          8         |        Dan         |      95
          6         |        Tom         |      75
          11        |        Bob         |      65
          3         |        Ace         |      60

mySQL查询的内容是什么?

3 个答案:

答案 0 :(得分:1)

您可以使用MAX()并按

排序
SELECT id,name,MAX(balance) AS  balance
FROM table
GROUP BY name
ORDER BY balance DESC

Fiddle

答案 1 :(得分:1)

也许是这样的:

select pid, name, max(balance) as highest_balance from my_table
group by pid, name
order by max(balance) desc;

答案 2 :(得分:0)

SELECT DISTINCT(b1.pid),b1.name,b1.balance FROM balance b1 WHERE balance =(SELECT MAX(b2.balance)FROM balance b2 WHERE b1.pid = b2.pid)ORDER BY balance DESC

OR

SELECT pid,name,MAX(balance)FROM balance GROUP BY pid ORDER BY balance DESC