带有多个非透视列的T-SQL数据透视表

时间:2012-10-02 07:32:11

标签: sql-server sql-server-2008 tsql pivot

我有几个专栏并制作支点。我想拥有多个非透视列,并使用最后一个进行透视。在原始规范here中,显示您只能有一个非透视列。

SELECT <non-pivoted column>,

    [first pivoted column] AS <column name>,

    [second pivoted column] AS <column name>,

    ...

    [last pivoted column] AS <column name>

FROM

    (<SELECT query that produces the data>)

    AS <alias for the source query>

PIVOT

(

    <aggregation function>(<column being aggregated>)

FOR

[<column that contains the values that will become column headers>]

    IN ( [first pivoted column], [second pivoted column],

    ... [last pivoted column])

) AS <alias for the pivot table>

<optional ORDER BY clause>;

是否有办法拥有更多非透视列,因为它在第一列之后使用所有列旋转我的数据。

1 个答案:

答案 0 :(得分:2)

是。只需添加它们。

例如

declare @t table (a int, b int, c int, d int)
insert @t values (1,2,3,4)
insert @t values (7,6,5,3)

select a,b, [3],[4] from @t s
pivot 
(sum(c) for d in ([3],[4])) p