SUM 或 SUBTRACTION 根据 mysql 查询中的条件 [英] SUM or SUBTRACTION upon condition in mysql query

查看:46
本文介绍了SUM 或 SUBTRACTION 根据 mysql 查询中的条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 mysql 查询中的某些条件下执行 SUM 或 SUBTRACTION.这是:SQLFiddle

I want to do SUM or SUBTRACTION upon certain condition within mysql query. This is : SQLFiddle

条件:

如果 ce_typeIN OR NULL 然后在变量中添加 payment_amount

if ce_type is IN OR NULL then add payment_amount in a variable

如果 ce_typeOUT 那么我想从那个变量中减去 payment_amount.

if ce_type is OUT then i want to subtract payment_amount from that variable.

我用这个查询试过了.但是,我不知道如何在这里放置条件.

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';

这篇关于SUM 或 SUBTRACTION 根据 mysql 查询中的条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆