需求:我想根据不同的条件,去查询某个表中同一个字段的不同的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"