简体   繁体   中英

Sum of values in a column for all distinct values in another column in SQL

I have a table like this:

ID | Value | Person

1  | 10    | Roy
1  | 10    | Sam
1  | 10    | Willis
2  | 50    | Troy
2  | 50    | Loy

I want to get some of "Value" column for all distinct IDs. So in the above example, the result should be 60 (ie, 10+ 50).

I tried doing sum(value) over (partition by ID) but that's not giving the desired result.

Please let me know how I can achieve this.

I'm trying to do this in PostgreSQL by the way.

You can use two levels of aggregation:

select sum(avg_value)
from (select id, avg(value) as avg_value
      from t
      group by id
     ) id;

尝试

select sum(value) from table group by (id, value)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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