转置键值对SQL表

时间:2012-06-27 11:14:58

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

我有一个由几列组成的表,包括键值配对。想象一下:

BookID, Key, Value
MyBook, Price, 19.99
MyBook, ISBN, 987878495793
MyBook, Pages, 354
MyBook2, ...., ....
MyBook2, ...., ....

我需要将其转换为以下格式:

BookID, Price, ISBN, Pages
MyBook, 19.99, 987878495793, 354
MyBook2,.....,.............,....

即转置单元格 - 我将如何在SQL中执行此操作?

1 个答案:

答案 0 :(得分:5)

这样的东西?

SELECT
  BookID, Price, ISBN, Pages
FROM
(
  SELECT BookID, Key, Value FROM yourTable
)
  AS SourceTable
PIVOT
(
  SUM(Value) FOR Key IN (Price, ISBN, Pages)
)
  AS PivotTable
ORDER BY
  BookID

http://technet.microsoft.com/en-us/library/ms177410(SQL.105).aspx