使用条件选择和求和来选择distinc行

时间:2019-06-02 12:19:59

标签: mysql

我有一个无法选择的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

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

您需要group by 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           |