简体   繁体   中英

MySQL SUM only if one of the columns contain a certain value

Is there a way to sum rows only when one of the columns has a certain value? I have this table:

| order_id | total | is_tip |
-----------------------------
|     1    |  12   |    1   |
|     1    |   3   |    0   |
|     2    |  28   |    0   |
|     2    |  15   |    0   |
|     3    |  39   |    1   |
|     3    |   8   |    1   |

The desired result would be:

| order_id | SUM(total) |
-------------------------
|     1    |     15     |
|     3    |     47     |

It would only sum up if one of the is_tip columns is equal to 1. So order IDs 1 and 3 are qualified. So far I've tried to use this query:

SELECT order_id, SUM(total) FROM orders HAVING COUNT(is_tip) >= 1;

But this query is so wrong. I'm just a beginner. Thank you in advance.

Use a having clause:

SELECT order_id, SUM(total)
FROM orders
GROUP BY order_id
HAVING SUM(is_tip) >= 1;

Your query also needs a GROUP BY . And I'm assuming you want a row with at least one "tip". You can also phrase the HAVING clause as:

HAVING MAX(is_tip) > 0

Please use below query,

SELECT order_id, SUM(total) FROM orders where is_tip >= 1 group by order_id;

Having can be used only where you want to filter on aggregation basis

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM