来自多维的MySQL Sum数据

时间:2019-08-08 10:19:22

标签: mysql sql

我遇到了一个问题,我需要基于多个维度对数据求和,源数据如下所示:

![enter image description here

目标是创建如下结果:

> Bank_name   total_issuer_fee   total_acq_fee   total_biller_fee   total_sw_fee
  BRI         xxx                xxx             xxx                xxx
  BNI         xxx                xxx             xxx                xxx
  MDR         xxx                xxx             xxx                xxx
  BTN         xxx                xxx             xxx                xxx

这是我的代码,用于在上图中生成数据:

select
issuer, acquirer, biller,
sum(total_issuer_fee) as total_issuer_fee,
sum(total_acq_fee) as total_acq_fee,
sum(total_biller_fee) as total_biller_fee,
sum(total_sw_fee) as total_sw_fee
from <source_table>
group by issuer, acquirer, biller;

感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

您可以尝试一下,我假设您的预期输出中的Bank_name是来自查询的issuer。因此,您在最终输出中不需要其他列。

select
biller as Bank_name,
sum(total_issuer_fee) as total_issuer_fee,
sum(total_acq_fee) as total_acq_fee,
sum(total_biller_fee) as total_biller_fee,
sum(total_sw_fee) as total_sw_fee
from <source_table>
group by  biller;

答案 1 :(得分:0)

如果要计数个值,即对acquirerissuerbiller的每一行计数三次,则您可以使用union all

select bank,
       sum(total_issuer_fee) as total_issuer_fee,
       sum(total_acq_fee) as total_acq_fee,
       sum(total_biller_fee) as total_biller_fee,
       sum(total_sw_fee) as total_sw_fee
from ((select issuer as bank_name, t.*
       from t
      ) union all
      (select acquirer as bank_name, t.*
       from t
      ) union all
      (select biller as bank_name, t.*
       from t
      )
     ) b     
group by bank;