gpt4 book ai didi

mysql - 使用条件选择和求和选择不同的行

转载 作者:行者123 更新时间:2023-11-29 06:30:44 25 4
gpt4 key购买 nike

我有一个 MySQL 选择,但无法使其工作。我的简化 order 表如下所示:

+----+------------+----------------+-------+----------------+
| id | partner_id | personal_price | price | modified_price |
+----+------------+----------------+-------+----------------+
| 1 | 1 | 500 | 900 | NULL |
| 2 | 1 | 700 | 1100 | 1400 |
| 3 | 2 | 400 | 800 | NULL |
+----+------------+----------------+-------+----------------+

如果设置了,total_price 应该是 modified_price,如果没有设置,则应该是 price。我还想区分合作伙伴的行,汇总 total_pricepersonal_price 并将差异计算为 partner_price

结果应该如下所示:

+------------+-------------+----------------+---------------+
| partner_id | total_price | personal_price | partner_price |
+------------+-------------+----------------+---------------+
| 1 | 2300 | 1200 | 1100 |
| 2 | 800 | 400 | 400 |
+------------+-------------+----------------+---------------+

到目前为止,代码不起作用的是:

SELECT
DISTINCT partner_id,
SUM ( CASE WHEN price_modified IS NULL
THEN price
ELSE price_modified END ) as total_price,
SUM ( presonal_price ),
total_price - personal_price as parnter_price
FROM orders

感谢您的帮助

最佳答案

您需要按partner_id分组并且不使用不同的:

select
partner_id,
sum(coalesce(modified_price, price)) total_price,
sum(personal_price) personal_price,
sum(coalesce(modified_price, price) - personal_price) partner_price
from orders
group by partner_id

请参阅demo .
结果:

| partner_id | total_price | personal_price | partner_price |
| ---------- | ----------- | -------------- | ------------- |
| 1 | 2300 | 1200 | 1100 |
| 2 | 800 | 400 | 400 |

关于mysql - 使用条件选择和求和选择不同的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56414952/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com