![](/img/trans.png)
[英]MYSQL- How to sum values from one table into one field in another table?
[英]Derive SUM values from one table mysql
使用条件聚合:
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
请参阅演示。
结果:
| id | in | out |
| --- | --- | --- |
| 1 | 800 | 150 |
| 2 | 500 | 400 |
| 3 | 150 | 900 |
首先,使用子查询生成可以轻松总结的结果集。 此 UNION 为输入表的每一行生成两行
SELECT in id, `count` in, 0 out FROM `table`
UNION ALL
SELECT out id, 0 in, count out FROM `table`
这会从表格的前三行为您提供这样的结果
id in out
1 500 0
3 0 500
1 200 0
2 0 200
1 100 0
2 0 100
然后总结该子查询:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.