SQL表中列名的静态和动态值

时间:2014-08-07 06:26:50

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

检查下表:

--------------------------------
ID    Value    GroupName
--------------------------------
1     10       A
2     12       B
3     19       A
4     5        B
5     9        A
6     12       B
7     17       C
8     21       C
9     8        C
10    15       A
--------------------------------

我希望得到以下输出:

-------------------------
A     B      C
-------------------------
10    12     17
19    5      21
9     12     8
15    NULL   NULL
-------------------------

因此,'GroupName'字段中的所有值都将成为新列 有谁知道如何在SQL 2008中执行此操作?

谢谢。

1 个答案:

答案 0 :(得分:2)

请尝试使用PIVOT;以下给出的示例仅适用于3个静态值A, B and C

select [A], [B], [C] From(
    select 
        Value, GroupName, 
        ROW_NUMBER() over (partition by GroupName order by GroupName) RN
    From 
        tbl
)up pivot (sum(value) for GroupName in ([A], [B], [C]))x

对于动态值,

DECLARE @pivv NVARCHAR(MAX),@Query NVARCHAR(MAX)

SELECT @pivv=COALESCE(@pivv+',','')+ QUOTENAME(GroupName) 
from tbl group by GroupName

IF ISNULL(@pivv, '')<>''
set @Query=
    'select '+@pivv+' From(
        select 
            Value, GroupName, 
            ROW_NUMBER() over (partition by GroupName order by GroupName) RN
        From 
            tbl
    )up pivot (sum(value) for GroupName in ('+@pivv+'))x'

exec (@Query)

SQL Fiddle Demo