2017-07-27 8 views
0

基本的にこれらの列は一時表にありますが、動的列(支払方法)で列にグループ化し、行に合わせてお支払い方法に基づいて税額を合計します。 Taxカラムは常にそこにあるので、静的カラムと見なすことができます。列を行に転記して共通の列を集計します

Pay Method | Tax 
Cash   1.00 
Card   0.70 

どのように私はこれを達成します:動的な列は、変数@PaymentMethod = [キャッシュ]、[カード]、等...

Cash | Card | Tax 
3.00    0.50 
3.00    0.50 
     5.00  0.70 

期待される結果に格納されていますか?私はUNPIVOTを調べましたが、すべての支払い方法は同じTax Columnフィールドを共有しています。実際には合計したいフィールドです。

答えて

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

関連する問題