mysql怎么查询最大值的相同行数据?

数据表大概是以下这样,表头分别是(id,企业id,客户名称,交易金额)

ide_idcus_nameamount
11A10
21B50
32C30
42D20
53E10

现在想查询每个企业的最大交易金额的客户,预期结果如下:

1B
2C
3E

现在能想到的一个写法是:

select A.e_id,B.cus_name from (select e_id,max(amount) amt from table group by e_id) A left join table B on A.e_id=B.e_id and A.amt=B.amount

但是感觉比较麻烦,有什么更好的思路吗?

阅读 2.9k
3 个回答
MySQL [wakka]> select a.e_id, b.max_amount from cs as a, (select e_id,max(amount) as max_amount from cs as cs_tmp group by e_id) as b where a.e_id = b.e_id and a.amount = b.max_amount;
+------+------------+
| e_id | max_amount |
+------+------------+
|    1 |         50 |
|    2 |         30 |
|    3 |         10 |
+------+------------+
3 rows in set (0.00 sec)

MySQL [wakka]> select a.e_id, a.cus_name, b.max_amount from cs as a, (select e_id,max(amount) as max_amount from cs as cs_tmp group by e_id) as b where a.e_id = b.e_id and a.amount = b.max_amount;
+------+----------+------------+
| e_id | cus_name | max_amount |
+------+----------+------------+
|    1 | B        |         50 |
|    2 | C        |         30 |
|    3 | E        |         10 |
+------+----------+------------+
3 rows in set (0.00 sec)

做完才发现跟你的方案一样 :(, 貌似常规做法就是这样吧?

select 
  e_id,cus_name
from 
  xxx
where amount in (select max(amount) as am from xxx group by xxx.e_id)

sql 菜鸟写的语句,有点挫。

写不出来的sql我可能就直接在代码里处理了,所有数据搞出来,O(n)就能提取出所有的最大行。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题