简体   繁体   中英

Mysql SUM with case statement and multiple conditions

SUM( CASE WHEN items.items_status != 2 THEN items.items_amount 
ELSE 0
END) as ItemsAmount
FROM orders 
LEFT JOIN items ON orders.orders_id = items.orders_id
WHERE orders.orders_status = 1 
group by orders.orders_id 


I get the following:


|     orders_id       |    orders_amount |    orders_status  |     ItemsAmount  |
|---------------------|------------------|------------------ |------------------|
|          1          |         10500    |     1             |      10500       |
|          2          |         2500     |     1             |      1300        |

I would like to exclude orders when orders_amount = ItemsAmount. So i have to add another conditions and the first line should be excluded

My two table are ( orders and items ).

table: items

Item_id orders_id items_amount items_staus
1 1 10500 1
2 2 100 1
3 2 1200 1
4 2 200 2
5 3 5000 1

Table: orders

orders_id orders_status orders_amount
1 1 10500
2 2 2500
3 2 7000

You may try applying this filter using having clause eg

SUM( CASE WHEN items.items_status != 2 THEN items.items_amount 
ELSE 0
END) as ItemsAmount
FROM orders 
LEFT JOIN items ON orders.orders_id = items.orders_id
WHERE orders.orders_status = 1 
group by orders.orders_id 

HAVING SUM( CASE WHEN items.items_status != 2 THEN items.items_amount 
ELSE 0
END) != orders_amount

Easiest way to do this is just add:

having orders_amount <> ItemsAmount

after the group by.

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