SQL Server 2008数据透视表未获得正确的输出

时间:2014-09-17 11:10:56

标签: sql sql-server sql-server-2008

我想要这个输出

enter image description here

我希望通过PortFolio代码获得组的唯一性,但不能获得所需的输出。 我得到以下输出。请告诉我在哪里使用枢轴或获得正确的输出

enter image description here

这是我的查询

    select isnull('PortFolio Code: '+a.CPORTFOLIOCODE,'Total'),
(select sum(a.FOSAMT) where a.SZBUCKETCODE=1) as [Bucket :1],
(select sum(a.FOSAMT) where a.SZBUCKETCODE=2) as [Bucket :2],
(select sum(a.FOSAMT) where a.SZBUCKETCODE=3) as [Bucket :3] 
from dbo.COL_TRN_AGREEMENT a 
group by a.CPORTFOLIOCODE,a.SZBUCKETCODE 
with rollup

我尝试使用枢轴但未能通过。

1 个答案:

答案 0 :(得分:1)

通过汇总删除并进行基于案例的聚合。

select isnull('PortFolio Code: '+a.CPORTFOLIOCODE,'Total'),
sum(case when a.SZBUCKETCODE =1  then a.FOSAMT else 0 end ) as [Bucket :1],
sum(case when a.SZBUCKETCODE =2  then a.FOSAMT else 0 end ) as [Bucket :2],
sum(case when a.SZBUCKETCODE =3  then a.FOSAMT else 0 end ) as [Bucket :3]
from dbo.COL_TRN_AGREEMENT a 
group by a.CPORTFOLIOCODE