我希望使用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
答案 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];
答案 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