如何用列切换行值?

时间:2016-04-29 09:44:27

标签: sql-server-2012

我有一个表存储我的数据:

ID   Name   Value 
1    Tag1   20  
2    Tag2   30
3    Tag3   40

我想像这样显示每个标签的值:

ID  Tag1  Tag2  Tag3
1   20    30    40

我在一栏中试过这个:

SELECT        
    ID
   ,Value AS Tag1
FROM
    dbo.TableLogger
WHERE
    (Name = 'Tag1')

我怎么能为剩下的列做?

1 个答案:

答案 0 :(得分:0)

SELECT ID,
[Tag1], [Tag2], [Tag3]
FROM
(SELECT ID, Value,Name
    FROM TableLogger) AS SourceTable
PIVOT
(
MAX(Value)
FOR Name IN ([Tag1], [Tag2], [Tag3])
) AS PivotTable;