样本数据
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
- 名字不固定可以允许很多名字
样本数据
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
像这样的东西怎么样
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
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