注意,你可以只用一个 CTE 来做到这一点,但我认为这很清楚。请记住,我没有在服务器上进行测试,因此可能存在错误或拼写错误。
WITH ranked AS
(
SELECT buyerID, ROW_NUMBER() OVER(PARTITION BY buyerID) AS ItemRank
FROM boughtItems
), allColumns AS
(
SELECT buyerID, i1.ItemID as item1, i2.ItemID as item2, i3.ItemID as item3, i4.ItemID as item4, i5.ItemID as item5
FROM ranked r
LEFT JOIN boughtItems item1 ON r.buyerID = item1.buyerID and ItemRank = 1
LEFT JOIN boughtItems item2 ON r.buyerID = item2.buyerID and ItemRank = 2
LEFT JOIN boughtItems item3 ON r.buyerID = item3.buyerID and ItemRank = 3
LEFT JOIN boughtItems item4 ON r.buyerID = item4.buyerID and ItemRank = 4
LEFT JOIN boughtItems item5 ON r.buyerID = item5.buyerID and ItemRank = 5
)
INSERT INTO denormalized (buyerid, item1, item2, item3, item4, item5)
SELECT buyerid, item1, item2, item3, item4, item5
FROM allColumns