【发布时间】:2020-05-06 10:36:26
【问题描述】:
我有下表,其中输入/输出列具有 ID 值。
我想获得下表,分别汇总输入和输出的“计数”。
Id 1 in = 500 + 200 + 100 = 800 |出 = 100 + 50 = 150
有没有更简单的方法来实现这一点?
【问题讨论】:
-
请不要在问题中使用图片来展示数据。
我有下表,其中输入/输出列具有 ID 值。
我想获得下表,分别汇总输入和输出的“计数”。
Id 1 in = 500 + 200 + 100 = 800 |出 = 100 + 50 = 150
有没有更简单的方法来实现这一点?
【问题讨论】:
首先,使用子查询生成一个您可以轻松总结的结果集。这个 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
【讨论】:
使用条件聚合:
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
请参阅demo。
结果:
| id | in | out |
| --- | --- | --- |
| 1 | 800 | 150 |
| 2 | 500 | 400 |
| 3 | 150 | 900 |
【讨论】: