![](/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.