我继承了一个表结构,我查询后得到下表:
---------------------------------------------------
| 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)会更好。
如果我能澄清任何事情,请告诉我。
最佳答案
这里假设只购买一个 bundle 。否则你需要一些东西来进行配对。
- 首先,您创建一个字段 category_type,以便将 bundle 组合在一起。
- 然后用array_agg把它们放在一起
- 最后加入正常产品的 bundle 。
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"
关于sql - PostgreSQL:有条件地合并两行的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46697634/