简体   繁体   中英

Mysql get sum of column_1 based on distinct value in column_2

I have this table:


+-----+--------+ 
|col1 |   col2 |
+-----+--------+
|   1 |     12 | 
|   1 |     12 |
|   2 |     13 |
|   4 |     15 | 
|   2 |     13 |
|   3 |     14 |
|   3 |     14 |
|   1 |     12 |
+-----+--------+

I'm looking for Total sum of col2 for distinct col1.

select col1, sum(col2) from mytable group by col1

With:

SELECT DISTINCT col1, col2 FROM tablename

get the distinct rows of the table and then get the sum:

SELECT SUM(col2) AS total
FROM (SELECT DISTINCT col1, col2 FROM tablename) t

then you just have to add another query select sum(col2) from myTable

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