2017-07-27 14 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