我想在mysql查询中的某些条件下进行SUM或SUBTRACTION。 这是:SQLFiddle
条件:
如果ce_type
为IN
或NULL
,则在变量中添加payment_amount
和
如果ce_type
为OUT
,那么我想从该变量中减去payment_amount
。
我尝试了这个查询。但是,我不知道如何把条件放在这里。
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'
答案 0 :(得分:4)
如果我理解正确,您只需要条件聚合:
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';
答案 1 :(得分:3)
如果 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';
答案 2 :(得分: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'
答案 3 :(得分:0)
您可以使用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'