具有透视数据的阶梯行为

时间:2010-10-04 14:05:38

标签: sql sql-server sql-server-2005 pivot pivot-table

向其他程序员和查询编写者致敬,

我有这个漂亮的查询

SELECT ID, [1] AS coL1, [15] AS coL2, [2] AS coL3, [16] AS coL4, [12] AS coL5
FROM MY_TABLE
PIVOT (sum(INT_VALUE) FOR FUND_CODE IN ([1],[2],[15],[16],[12])) AS p
--GROUP BY ID, [1] , [15]  , [2] , [16] , [12] 
ORDER BY ID ASC

这会返回我这样的数据:

10001      182       NULL      NULL      NULL
10001      NULL      81        NULL      NULL
10001      NULL      NULL      182       NULL
10001      NULL      NULL      NULL      81
10002      165       NULL      NULL      NULL
10002      NULL      73        NULL      NULL
10002      NULL      NULL      165       NULL
10002      NULL      NULL      NULL      73

10001和10002是两个主键,我想像这样显示我的数据:

10001      182       81      182      81
10002      165       73      165      73

我试过这个评论的GROUP BY无济于事。 任何提示?它涉及COALESCE吗?

2 个答案:

答案 0 :(得分:2)

SELECT ID      ,SUM(1)AS'col1'          ,SUM(15)AS'col2'      ,SUM(2)AS'col3'      ,SUM(16)AS'col4'          ,SUM(12)AS'col5' FROM表GROUP BY ID

答案 1 :(得分:0)

就在CASE ......

SELECT ID,
SUM(CASE WHEN FUND_CODE = 1 THEN VR_MOVIMENTACAO_QUOTA ELSE 0 END) coL1,
SUM(CASE WHEN FUND_CODE = 15 THEN VR_MOVIMENTACAO_QUOTA ELSE 0 END) coL2,
SUM(CASE WHEN FUND_CODE = 2 THEN VR_MOVIMENTACAO_QUOTA ELSE 0 END) coL3,
SUM(CASE WHEN FUND_CODE = 16 THEN VR_MOVIMENTACAO_QUOTA ELSE 0 END) coL4,
SUM(CASE WHEN FUND_CODE = 12 THEN VR_MOVIMENTACAO_QUOTA ELSE 0 END) coL5

FROM MY_TABLE
GROUP BY ID