0

样本数据

 date     | num | name | value
 01012012 |  1  |    A |  20
 01012012 |  1  |    B |  30
 01012012 |  2  |    C |  40

希望喜欢这个

 date     | num |  A |  B |  C
 01012012 |   1 | 20 | 30 | --
 01012012 |   2 | -- | -- | 40
  • 名字不固定可以允许很多名字
4

2 回答 2

2

像这样的东西怎么样

DECLARE @Table TABLE(
        date DATETIME,
        num INT,
        name VARCHAR(20),
        value FLOAT
)
INSERT INTO @Table SELECT '20121201',1,'A',20
INSERT INTO @Table SELECT '20121201',1,'B',30
INSERT INTO @Table SELECT '20121201',2,'C',40

SELECT  *
FROM    (
            SELECT  date,
                    num,
                    name,
                    value
            FROM    @Table
        ) t
PIVOT   (
            SUM(Value) FOR name IN ([A],[B],[C])
        ) p

SQL 小提琴演示

于 2012-11-02T08:18:30.373 回答
2

对于动态列,您需要使用动态 SQL

SQL 提琴示例

declare
    @cols nvarchar(max),
    @stmt nvarchar(max)

select @cols = isnull(@cols + ', ', '') + '[' + Name + ']' from table1

select @stmt = '
    select *
    from table1 as T
        pivot 
        (
            max(T.value)
            for name in (' + @cols + ')
        ) as P'

exec sp_executesql  @stmt = @stmt

如果您不需要动态列数,则可以使用普通 SQL,例如

select *
from table1 as T
    pivot 
    (
        max(T.value)
        for name in ([A],[B],[C])
    ) as P
于 2012-11-02T08:22:21.260 回答