牛骨文教育服务平台(让学习变的简单)
博文笔记

MySql中,求一张表中同字段不同条件的sum值

创建时间:2016-09-21 投稿人: 浏览次数:1734

需求:我想根据不同的条件,去查询某个表中同一个字段的不同的sum值

解决:

1、首先有3张表,如下图

2、问题:我想查询fina_finaflow 表中finaflow_amount两个不同条件不同的sum值。

3、方案:sql语句如下:

select 
    sum(a.finaflow_amount) AS sumCome 
from
    fina_finaflow a
    join fina_finaflow b ON a.id = b.id
    right join fina_contract_mainbill c on a.mainbillid = c.id
    left join fina_finaflow_property d on a.finaflow_prop = d.id
where 
    c.id in (select id from fina_contract_mainbill where mainbilltype = 1)
    and d.proptype = 1
    and a.communityid = 5
    and a.customerid = 1 
    and a.occuryear >= "2016-09-19"

union all 

select 
    sum(b.finaflow_amount) AS sumAmount
from
    fina_finaflow a
    join fina_finaflow b ON a.id = b.id
    right join fina_contract_mainbill c on a.mainbillid = c.id
    left join fina_finaflow_property d on a.finaflow_prop = d.id
where 
    c.id in (select id from fina_contract_mainbill where mainbilltype = 1)
    and d.propname <> "定金" 
    and d.propname <> "押金" 
    and d.proptype = 2
    and a.communityid = 5
    and a.customerid = 1
    and a.occuryear >= "2016-09-19"
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。