一尘不染

转置键值对SQL表

sql

我有一个表,其中包含几列,包括一个键值对。想象一下:

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中做到这一点?


阅读 227

收藏
2021-03-10

共1个答案

一尘不染

像这样吗?

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/zh-
cn/library/ms177410(SQL.105).aspx

2021-03-10