2017-02-23 16 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

可以使用聚合函數sum(或max按你的需求)來實現這一目標。

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 
相關問題