SSMS - 透视列并更改字段名称

时间:2013-02-15 20:11:32

标签: sql tsql ssms

说我有下表,表1

SIMULATION  STATEMENT_LINE                  PERIOD  OUTPUT_YTDIncStmt
0           A_1_a_Gross_Written_Premium     2012Q2  1362419134
0           A_Net_Earned_Premium            2012Q2  0
0           A_1_Gross_Earned_Premium        2012Q2  1362419134

有什么方法可以转动STATEMENT_LINE列,而不是拥有所有A_1而不是A_1,我可以让它看起来像......

PERIOD    [Gross Written Premium]    [Net Earned Premium]    [Gross Earned Premium]
2012Q2          1362419134                    0                     1362419134   

我想亲自指定要调用的列,而不仅仅是删除“_”和“A”或“1”。

这样做的好方法是什么?

1 个答案:

答案 0 :(得分:1)

你可以这样做。

SELECT [Period],
    [A_1_a_Gross_Written_Premium] AS [Gross Written Premium],
    [A_Net_Earned_Premium] AS [Net Earned Premium],
    [A_1_Gross_Earned_Premium] AS [Gross Earned Premium]
FROM
  (
   SELECT [STATEMENT_LINE], [PERIOD], [OUTPUT_YTDIncStmt]
   FROM Table1
   ) AS Source

PIVOT
  (
   MAX(OUTPUT_YTDIncStmt)
   FOR STATEMENT_LINE IN ([A_1_a_Gross_Written_Premium], [A_Net_Earned_Premium], [A_1_Gross_Earned_Premium])
  ) AS PivotTable