提问人:Ann 提问时间:12/8/2021 最后编辑:marc_sAnn 更新时间:12/8/2021 访问量:96
如何在SQL中将行变成列
How to make rows into columns in SQL
问:
我有这张桌子
SELECT PolicyID, ItemID, Period, Inventory1, Inventory2
FROM tblInventory
我想将此表转换为:
该期间将转换为列,例如 Inventory1 -1 和 Inventory2 -1,直到第 4 个期间,每个期间包括两列:inventory1 和 inventory2。
我想请帮助了解如何在 SQL 中对此进行编码。谢谢!
答:
0赞
Chris Albert
12/8/2021
#1
SELECT
*
FROM
(
SELECT
UP.PolicyId
, UP.ItemId
, CONCAT(UP.Inventories, '-', UP.Period) AS Inventories
, UP.Inventory
FROM
tblInventory AS TI
UNPIVOT
(
Inventory FOR Inventories IN (Inventory1, Inventory2)
) AS UP
) AS UNP
PIVOT
(
MAX(Inventory)
FOR Inventories IN
(
[Inventory1-1], [Inventory1-2], [Inventory1-3], [Inventory1-4]
, [Inventory2-1], [Inventory2-2], [Inventory2-3], [Inventory2-4]
)
) AS PVT
评论
PIVOT