2017-07-27 13 views
0

基本上我有这些列在临时表中,我想通过动态列(付款方式)将它们分组到行中,并基于付款方法总结税额。 Tax列将始终存在,因此您可以将其视为一个静态列。动态列存储在一个变量@PaymentMethod = [现金],[卡],等等移动列到行并总结普通列

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,所有付款方式共享相同的税收栏位,这实际上是我想总结的栏位。

回答

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); 
+0

我不能用这种方式,因为支付方式将是动态的。你很难编码付款方式。 – user3543512

+0

@ user3543512。 。 。如果他们是表格中的列,他们实际上不会是动态的。 –

+0

他们是临时表。比方说,这些列都存储在一个变量@PaymentMethod = [现金],[信贷]等 – user3543512