简体   繁体   English

Mysql SUM 与 case 语句和多个条件

[英]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.我想在 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 item_id orders_id订单编号 items_amount items_amount items_staus items_staus
1 1 1 1 10500 10500 1 1
2 2 2 2 100 100 1 1
3 3 2 2 1200 1200 1 1
4 4 2 2 200 200 2 2
5 5 3 3 5000 5000 1 1

Table: orders表:订单

orders_id订单编号 orders_status订单状态 orders_amount订单金额
1 1 1 1 10500 10500
2 2 2 2 2500 2500
3 3 2 2 7000 7000

You may try applying this filter using having clause eg您可以尝试使用 have 子句应用此过滤器,例如

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.分组后。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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