如何在SQL Server 2005中切换行和列?

时间:2012-02-10 07:20:29

标签: sql-server-2005 pivot

我在这里看到过很多行到列的线程,但找不到我正在寻找的内容。

如何转换下表:

ID    Foo    Bar
1     A      F
2     B      G
3     C      H
4     D      I
5     E      J

进入这个:

ID    1    2    3    4    5
Foo   A    B    C    D    E
Bar   F    G    H    I    J

谢谢!我顺便使用SQL Server 2005。

1 个答案:

答案 0 :(得分:0)

这是 的答案。正如我在评论中提到的那样,这只适用于您正在使用的维度已知/已修复。首先,样本数据:

declare @Table table (ID int not null,Foo char(1) not null,Bar char(1) not null)
insert into @Table (ID,Foo,Bar)
select 1,'A','F' union all
select 2,'B','G' union all
select 3,'C','H' union all
select 4,'D','I' union all
select 5,'E','J'

select * from @Table --As per your original data table

;with Rot1 as (
    select
        *
    from
        @Table unpivot (Value for Col in (Foo,Bar)) t
)
select * from Rot1 -- See below

;with Rot1 as (
    select
        *
    from
        @Table unpivot (Value for Col in (Foo,Bar)) t
), Rot2 as (
    select
        *
    from Rot1 pivot (MAX(Value) for ID in ([1],[2],[3],[4],[5])) t
)
select * from Rot2 -- As per your required result

仅从Rot1中选择时的输出是:

ID  Value   Col
1   A   Foo
1   F   Bar
2   B   Foo
2   G   Bar
3   C   Foo
3   H   Bar
4   D   Foo
4   I   Bar
5   E   Foo
5   J   Bar

因此,我们可以构建此查询,只要我们知道交叉引用标识符的所有,例如FooBar12345。在大多数想要进行这种转换的情况下,你并不知道所有这些值,因此SQL不是实现转换的方法 - 使用任何消耗原始结果的工具来实现这种重新格式化。