从一个表mysql派生SUM值

时间:2020-05-06 10:36:26

标签: mysql join sum pivot

我有一张下表,其中in / out列具有ID值。

enter image description here

我想获得下面的表格,其中分别汇总了“计数”的输入和输出。

enter image description here

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

有没有更简单的方法来实现这一目标?

2 个答案:

答案 0 :(得分:1)

有条件聚合:

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 |

答案 1 :(得分:1)

首先,使用子查询生成结果集,您可以轻松地对其进行汇总。该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
相关问题