0

我有下表:

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]
4

1 回答 1

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;
于 2012-07-19T19:27:44.690 回答