[英]SUM or SUBTRACTION upon condition in mysql query
I want to do SUM or SUBTRACTION upon certain condition within mysql query. 我想在mysql查询中的某些条件下进行SUM或SUBTRACTION。 This is : SQLFiddle 这是: SQLFiddle
Condition: 条件:
if ce_type
is IN
OR NULL
then add payment_amount
in a variable 如果ce_type
为IN
OR NULL
则在变量中添加payment_amount
and 和
if ce_type
is OUT
then i want to subtract payment_amount
from that variable. 如果ce_type
是OUT
那么我想从该变量中减去payment_amount
。
I tried it with this query. 我用这个查询试了一下。 But, I don't know how to put condition here. 但是,我不知道如何把条件放在这里。
SELECT SUM(payment_amount) as payment_amount
FROM customer_payment_options
WHERE (real_account_id='11' AND real_account_type='HQ')
AND company_id='1'
You just want conditional aggregation, if I understand correctly: 如果我理解正确,您只需要条件聚合:
SELECT SUM(CASE WHEN ce_type = 'IN' or ce_type is NULL then payment_amount
WHEN ce_type = 'OUT' then - payment_amount
END) as payment_amount
FROM customer_payment_options
WHERE real_account_id = '11' AND real_account_type = 'HQ' AND company_id = '1';
IF ce_type can only have the values NULL , IN and OUT , the following statement does the job. 如果ce_type只能具有值NULL , IN和OUT ,则以下语句执行该作业。
SELECT SUM(IF(ce_type = 'IN' OR ce_type is NULL,payment_amount,-payment_amount)) as payment_amount
FROM customer_payment_options
WHERE (real_account_id='11' AND real_account_type='HQ')
AND company_id='1';
SELECT SUM(
CASE WHEN ce_type IS NULL THEN 1 ELSE
CASE ce_type WHEN 'IN' THEN 1 ELSE -1 END
END
* payment_amount) as payment_amount
FROM customer_payment_options
WHERE (real_account_id='11' AND real_account_type='HQ')
AND company_id='1'
You can use IF()
to change it conditionally: 您可以使用IF()
有条件地更改它:
SELECT SUM(IF(ce_type = "OUT", -1 * payment_amount, payment_amount)) as payment_amount
FROM customer_payment_options
WHERE (real_account_id='11' AND real_account_type='HQ')
AND company_id='1'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.