t-sql将行转置为列

时间:2014-09-28 12:07:49

标签: sql sql-server

我在创建查询时遇到了一些问题,我将行转换为列。 例如,我有以下表格:

UniqueId                               | PropertyName   | PropertyValue  | Time
--------------------------------------------------------------------------------------------------
EA91B396-A3DE-4A16-850B-30D7CD45D753   | FileName       | Test.txt       | 2014-09-26 19:12:58.203
EA91B396-A3DE-4A16-850B-30D7CD45D753   | SourceLocation | C:\Temp        | 2014-09-26 19:12:58.203
1036E17B-3527-4F26-9ABD-565DF98C7A98   | FileName       | Test2.txt      | 2014-09-26 19:15:02.215
1036E17B-3527-4F26-9ABD-565DF98C7A98   | SourceLocation | C:\Temp2       | 2014-09-26 19:15:02.215

现在我想把这些数据转换成下表:

UniqueId                               | FileName       | SourceLocation  | Time
------------------------------------------------------------------------------------------------
EA91B396-A3DE-4A16-850B-30D7CD45D753   | Test.txt       | C:\Temp         | 2014-09-26 19:12:58.203
1036E17B-3527-4F26-9ABD-565DF98C7A98   | Test2.txt      | C:\Temp2        | 2014-09-26 19:15:02.215

基本上每个值都是" PropertyName"成为我的输出查询中的列和" PropertyValue"列成为该新列的值。 知道我怎么能做到这一点吗?

提前致谢!

2 个答案:

答案 0 :(得分:3)

查询

SELECT * 
FROM Table_Name T 
            PIVOT (
                   MAX(PropertyValue)
                   FOR PropertyName
                   IN ([FileName],[SourceLocation])
                   )p

结果

╔══════════════════════════════════════╦═════════════════════════╦═══════════╦════════════════╗
║               UniqueId               ║          Time           ║ FileName  ║ SourceLocation ║
╠══════════════════════════════════════╬═════════════════════════╬═══════════╬════════════════╣
║ EA91B396-A3DE-4A16-850B-30D7CD45D753 ║ 2014-09-26 19:12:58.203 ║ Test.txt  ║ C:\Temp        ║
║ 1036E17B-3527-4F26-9ABD-565DF98C7A98 ║ 2014-09-26 19:15:02.217 ║ Test2.txt ║ C:\Temp2       ║
╚══════════════════════════════════════╩═════════════════════════╩═══════════╩════════════════╝

答案 1 :(得分:1)

如果你知道PropertyName值是什么,你可以使用PIVOT并硬编码值:

SELECT [UniqueId], [FileName], [SourceLocation], [Time] 
FROM (
    SELECT [UniqueId], [PropertyName], [PropertyValue], [Time] 
    FROM Table1 
    ) SourceTable
PIVOT (
    MAX(PropertyValue) FOR PropertyName IN ([FileName], [SourceLocation])
) AS PivotedTable

如果PropertyName值可能不同,则需要使用动态SQL来构建PIVOT的属性列表:

DECLARE @SQL AS NVARCHAR(MAX)
DECLARE @COLS AS NVARCHAR(MAX)

SELECT @COLS= ISNULL(@COLS + ',','') + QUOTENAME(PropertyName)
FROM (SELECT DISTINCT PropertyName FROM Table1) AS Properties

SET @SQL =
  N'SELECT [UniqueId], ' + @COLS + ', [Time]
    FROM Table1
    PIVOT (
       MAX(PropertyValue) FOR PropertyName IN (' + @COLS + ')
       ) AS PivotedTable'

EXEC sp_executesql @SQL

Sample SQL Fiddle