SQL:将行转置为没有聚合函数的列

时间:2014-05-02 14:30:18

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

我希望使用SQL 2008转置以下数据。由于Pivot使用聚合,我认为不可能使用。

输入:

File    Date    Metadata    MetadataValue
R1      2-May   Name        Custom Report
R1      2-May   Format      txt
R1      2-May   Type        Report
R2      2-May   Name        Standard Report
R2      2-May   Format      pdf
R2      2-May   Type        Log
R1      3-May   Name        Custom Report
R1      3-May   Format      txt
R1      3-May   Type        Report
R2      3-May   Name        Standard Report
R2      3-May   Format      pdf
R2      3-May   Type        Log

输出:

File    Date    Name            Format  Type
R1      2-May   Custom Report   txt       Report
R2      2-May   Standard Report pdf       Log
R1      3-May   Custom Report   txt       Report
R2      3-May   Standard Report pdf       Log

2 个答案:

答案 0 :(得分:3)

仍然是一个聚合,但您可以为每个值使用一个简单的CASE语句,按[date], [file]分组以获得每个组合一行;

SELECT [file], [date], 
  MAX(CASE WHEN metadata='name'   THEN metadatavalue END) name,
  MAX(CASE WHEN metadata='format' THEN metadatavalue END) format,
  MAX(CASE WHEN metadata='type'   THEN metadatavalue END) type
FROM mytable
GROUP BY [date], [file]
ORDER BY [date], [file];

...或 可以真正使用PIVOT获得相同的结果;

SELECT [file], [date], [name], [format], [type]
FROM mytable
PIVOT (
  MAX(metadatavalue) FOR metadata IN ([name], [format], [type])
) b
ORDER BY [date], [file];

An SQLfiddle with both

答案 1 :(得分:1)

SELECT * 
FROM @TABLE t
 PIVOT (MAX(MetadataValue)
        FOR [MetaData]
        IN ([Name],[Format],[Type])
        )p

结果集

╔══════╦═══════╦═════════════════╦════════╦════════╗
║ File ║ Date  ║      Name       ║ Format ║  Type  ║
╠══════╬═══════╬═════════════════╬════════╬════════╣
║ R1   ║ 2-May ║ Custom Report   ║ txt    ║ Report ║
║ R2   ║ 2-May ║ Standard Report ║ pdf    ║ Log    ║
║ R1   ║ 3-May ║ Custom Report   ║ txt    ║ Report ║
║ R2   ║ 3-May ║ Standard Report ║ pdf    ║ Log    ║
╚══════╩═══════╩═════════════════╩════════╩════════╝

Working SQL Fiddle