2017-02-23 7 views
0

次のアクションに記述するための用語を知っているなら、私に助言してください:集計結果を列に変換する方法は?

入力

dfips dcounty  context sumton 
19001 Adair County mail 6521.79995560646 
19001 Adair County Rail 38411.5996840298 

出力:

dfips dcounty  mail_sumton  rail_sumton 
19001 Adair County 6521.79995560646 38411.5996840298 

を私は入力を出力に変換したいのですが、私はそのような行為をどのように記述するかについては不明です。私が思いつくことができる最高ののは、集計結果を列に変換することです。

答えて

2

pivot()の簡単なクロス集計バージョンは次のようになります。

select 
    dfips 
    , dcounty 
    , mail_sumton = sum(case when context = 'mail' then sumton else null end) 
    , rail_sumton = sum(case when context = 'rail' then sumton else null end) 
from t 
group by dfips, dcounty 
1

条件付き集約

select 
    dfips, 
    dcounty, 
    sum(case when context = 'mail' then isnull(sumton,0) else null end) as mail_sumton, 
    sum(case when context = 'rail' then isnull(sumton,0) else null end) as rail_sumton, 
from yourTable 
group by 
    dfips, dcounty 
1

あなたはこれを達成するために(あなたのニーズに従ってまたはmax)集約関数sumを使用することができます。

select 
    dfips, 
    dcounty, 
    sum(case when context = 'mail' then sumton end) mail_sumton, 
    sum(case when context = 'Rail' then sumton end) rail_sumton 
from your_table 
group by 
    dfips, 
    dcounty 
関連する問題