将列转置为行并汇总公共列

时间:2017-07-27 12:20:30

标签: sql database procedures

基本上我在临时表中有这些列,我想通过动态列(付款方式)将它们分组到行,并根据付款方式汇总税额。 Tax列将始终存在,因此您可以将其视为静态列。动态列存储在变量@PaymentMethod = [Cash],[Card]等...

Cash |  Card   | Tax
3.00             0.50
3.00             0.50
        5.00     0.70

预期结果:

Pay Method | Tax 
Cash         1.00 
Card         0.70

我如何实现这一目标?我已查看UNPIVOT但是,所有付款方式共享相同的税栏字段,实际上是我要总结的字段。

1 个答案:

答案 0 :(得分:0)

只需使用case进行汇总:

select (case when cash is null and card is null then 'neither'
             when cash is not null and card is not null then 'both'
             when cash is not null then 'cash'
             when credit is not null then 'credit'
        end) as pay_method,
       sum(tax)
from t
group by (case when cash is null and card is null then 'neither'
               when cash is not null and card is not null then 'both'
               when cash is not null then 'cash'
               when credit is not null then 'credit'
          end);