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.