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