繁体   English   中英

从一张表中导出 SUM 值 mysql

[英]Derive SUM values from one table mysql

我有下表,其中输入/输出列具有 ID 值。

在此处输入图像描述

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

在此处输入图像描述

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

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

使用条件聚合:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM