简体   繁体   English

MYSQL-不同行的总和

[英]MYSQL - Sum of distinct rows

I am new to MYSQL and need a simple query but can't get it to work. 我是MYSQL的新手,需要一个简单的查询,但无法正常工作。

I have a table 我有桌子

id   amount
 1      30
 2      20
 3      30
 3      30
 4      50

I want the sum of the amount for distinct ids 我想要不同ID的金额总和

So the output should simply be 130. (30+20+30+50) 因此输出应该只是130。(30 + 20 + 30 + 50)

How can I achieve this ? 我该如何实现?

Thanks. 谢谢。

You can use distinct 您可以使用不同的

select sum(amount) from (
select distinct `id`, `amount` from t
  ) t1

Demo 演示

or pick the max amount for same ids 或选择相同ID的最大金额

select sum(amount) from (
select `id`, max(`amount`) amount from t group by id
  ) t1

Demo 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM