对所购商品的数据进行非规范化

时间:2012-07-19 19:08:30

标签: sql-server database sql-server-2008-r2

我有下表:

BoughtItems 

UserID  ItemID  StoreID  Quantity  Price
1       1       1        1         1
1       4       1        2         3
1       5       2        1         3

我们假设BoughtItems表中的每个用户不超过五个项目。

我想拥有一些StoreID的所有客户端以及所购买的所有商品,格式为...对于StoreID = 1,结果将为:

UserID  Item1ID  Item2ID  Item3ID  Item4ID  Item5ID
1       1        4        [empty]  [empty]  [empty]

1 个答案:

答案 0 :(得分:2)

DECLARE @StoreID INT;

SET @StoreID = 1;

;WITH x AS
(
  SELECT UserID, ItemID, 
    rn = ROW_NUMBER() OVER (PARTITION BY UserID ORDER BY ItemID)
  FROM dbo.BoughtItems
  WHERE StoreID = @StoreID
)
SELECT UserID,
    Item1ID = MAX(CASE WHEN rn = 1 THEN ItemID END),
    Item2ID = MAX(CASE WHEN rn = 2 THEN ItemID END),
    Item3ID = MAX(CASE WHEN rn = 3 THEN ItemID END),
    Item4ID = MAX(CASE WHEN rn = 4 THEN ItemID END),
    Item5ID = MAX(CASE WHEN rn = 5 THEN ItemID END)
FROM x WHERE rn <= 5
GROUP BY UserID;