带有两个值列的数据透视表

时间:2015-01-13 12:31:40

标签: sql-server excel pivot multiple-columns

我可以在excel中完成这项工作,但无法在MSSQL 2012中复制。 简单表(在现实生活中是一个数据结果本身),它有四列具有以下值:

地区风险计数请求
North FM 7£35930.7
North SPV 14£133629.86
Scot FM 2£10822.5
Scot SPV 16£618555.93
南FM 2£544.96
南SPV 11£189079.8

结果需要如下所示:

区域FMCount FMRequest SPVCount SPVRequest
North 7£35,930.70 14£133,629.86
苏格兰人2£10,822.50 16£618,555.93
南2£544.96 11£189,079.80

2 个答案:

答案 0 :(得分:0)

使用Conditional Aggregate

SELECT Region,
       Max(CASE WHEN Risk = 'FM' THEN cnt END) FM_COUNT,
       Max(CASE WHEN Risk = 'FM' THEN request END) FM_REQUEST,
       Max(CASE WHEN Risk = 'SPV' THEN cnt END) SPV_COUNT,
       Max(CASE WHEN Risk = 'SPV' THEN request END) SPV_REQUEST
FROM   Yourtable
GROUP  BY Region 

答案 1 :(得分:0)

select
a.region, a.FMCount, b.FMRequest, a.SPVCount, b.SPVRequest
from
(
    select
    region, [FM] as FMCount, [SPV] as SPVCount
    from
    (select region, risk, sum(cnt) as cnt from data group by region, risk) a
    pivot (  sum(cnt) for Risk in ([FM], [SPV]) ) a
) a
inner join
(
    select
    region, [FM] as FMRequest, [SPV] as SPVRequest
    from
    (select region, risk, sum(request) as request from data group by region, risk) a
    pivot (  sum(request) for Risk in ([FM], [SPV]) ) a
) b 
on a.region = b.region