简体   繁体   中英

How to sum multiple rows?

I have a table like this: 'round' is kind of id

id  round  kind   count
1     1     1      10
1     1     2      10
1     1     1      20
1     2     1      10
1     2     1      30
2     1     1      15
2     1     1      10
2     2     2      20

I want these result

id  round  kind1Total  kind2Total   roundTotal
1     1    30           10            40
1     2    40                         40
2     1    25                         25
2     2                 20            20

Use conditional aggregation:

SELECT
    id,
    round,
    SUM(IF(kind=1, count, 0)) AS kind1Total,
    SUM(IF(kind=2, count, 0)) AS kind2Total,
    SUM(count) AS roundTotal
FROM yourTable
GROUP BY
    id,
    round
ORDER BY
    id,
    round;

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