簡體   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