sql - PostgreSQL:有条件地合并两行的值

标签 sql postgresql

我继承了一个表结构,我查询后得到下表:

---------------------------------------------------
| 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 。

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"

关于sql - PostgreSQL:有条件地合并两行的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46697634/

相关文章:

python - 找不到 SQL 服务器

postgresql - 如何在 postgresql 中以弹性方式删除触发器

php - 尝试在mysql查询中显示最大时间记录

sql - Hive SQL Integer YYYYMM 前几个月

postgresql - 如何在 postgresql 中使用不同的 WHERE 语句按组进行两个单独的计数?

sql - 如何让事件用户通过 SQL 连接到 postgreSQL 数据库?

sql - 如何根据多个外键选择数据库条目?

sql - 为什么此 Postgres Select Query 在本地 Docker 容器中有效,但在 Amazon RDS Postgres 中无效?

php - MySQL 将多行查询连接到一列中

sql - 如何在不使用 CDC 功能的情况下在单个表中维护多个表的历史记录