简体   繁体   中英

Derive SUM values from one table mysql

I have following table where in/out columns have ID values.

在此处输入图像描述

I want to get following table aggregating "count" for in and out separately.

在此处输入图像描述

Id 1 in = 500 + 200 + 100 = 800 | out = 100 + 50 = 150

Is there a simpler way to achieve this?

With conditional aggregation:

select 
  coalesce(`in`, `out`) id,
  sum(case when `in` is not null then count end) `in`,
  sum(case when `out` is not null then count end) `out`
from (
  select `in`, null `out`, count from tablename 
  union all 
  select null `in`, `out`, count from tablename 
) t
group by id 

See the demo .
Results:

| id  | in  | out |
| --- | --- | --- |
| 1   | 800 | 150 |
| 2   | 500 | 400 |
| 3   | 150 | 900 |

First, use a subquery to generate a result set you can summarize easily. This UNION generates two rows for each row of your input table

         SELECT in id, `count` in, 0 out FROM `table`
          UNION ALL
          SELECT out id, 0 in, count out FROM `table`

This gives you a result like this from the first three rows of your table

   id    in    out
    1    500     0
    3      0   500
    1    200     0
    2      0   200
    1    100     0
    2      0   100

Then summarize that subquery:

    SELECT id, SUM(in) in, SUM(out) out
      FROM (  SELECT in id, `count` in, 0 out FROM `table`
               UNION ALL
              SELECT out id, 0 in, count out FROM `table`
           ) a
     GROUP BY id

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