我继承了一个我查询过的表结构,导致下表:
---------------------------------------------------
| purchase | item | price | category |
---------------------------------------------------
| 1 | widget A | 20.00 | product |
| 1 | widget B | 50.00 | product |
| 2 | widget A | 20.00 | product |
| 3 | widget A | 20.00 | product |
| 3 | promo | 30.00 | product |
| 3 | widget B | 0.00 | bundle |
---------------------------------------------------
我正在尝试提取一个特定的报告,该报告将捆绑的产品组合到促销项目的结果中(因为它们是相关的),这样看起来像这样:
----------------------------------------------------------
| purchase | item | price | category |
----------------------------------------------------------
| 1 | widget A | 20.00 | product |
| 1 | widget B | 50.00 | product |
| 2 | widget A | 20.00 | product |
| 3 | widget A | 20.00 | product |
| 3 | promo - widget B | 30.00 | product |
----------------------------------------------------------
对于任何类别为“捆绑”的商品,价格将为0.00,并且相应的促销商品将作为同一购买的一部分。现在,我可以假设每次购买只有一个捆绑产品,但是可以将多个捆绑项目连接到一个促销的解决方案(例如'促销 - 小部件B,小部件C)会更好。
如果我能说清楚的话,请告诉我。
答案 0 :(得分:2)
这假设只有一个捆绑购买。否则你需要一些东西来配对。
<强> SQL DEMO 强>
WITH cte as (
SELECT *, CASE WHEN "item" = 'promo' OR "category" = 'bundle'
THEN 'bundle'
ELSE 'product'
END as category_type
FROM purchases
), bundle as (
SELECT purchase,
array_to_string(array_agg(item ), ' - ') as "item",
MAX(price) as price,
MAX(category) as category
FROM cte
WHERE category_type = 'bundle'
GROUP BY purchase
)
SELECT * FROM bundle
UNION ALL
SELECT "purchase", "item", "price", "category"
FROM cte
WHERE category_type <> 'bundle'
ORDER BY "purchase"