如何求和联合查询结果?

时间:2015-05-09 16:35:57

标签: mysql sum union

直升机, 我有这样的查询:

SELECT 
if (cf_1095-accountingpaidamount>0,FORMAT(cf_1095-accountingpaidamount, 0, 'de_DE'),0) as Kurang_Gesek

FROM vtiger_servicecontracts, vtiger_crmentity, vtiger_servicecontractscf, vtiger_campaign, vtiger_contactdetails, vtiger_accounting, vtiger_accounting_payments

WHERE
vtiger_accounting_payments.idtransaction=vtiger_accounting.accountingid
and
vtiger_accounting.accountingrelated2=vtiger_servicecontracts.servicecontractsid
and
vtiger_contactdetails.contactid=vtiger_servicecontracts.contactid and
vtiger_campaign.campaignid=cf_1155
and vtiger_crmentity.crmid=vtiger_servicecontracts.servicecontractsid
and vtiger_servicecontractscf.servicecontractsid=vtiger_servicecontracts.servicecontractsid
and accountingtype="Pelunasan Gesek"
group by campaignname

UNION

SELECT 
if (cf_1095>0,FORMAT(cf_1095, 0, 'de_DE'),0) as Kurang_Gesek

FROM vtiger_servicecontracts, vtiger_crmentity, vtiger_servicecontractscf, vtiger_campaign, vtiger_contactdetails, vtiger_accounting, vtiger_accounting_payments

WHERE
vtiger_accounting_payments.idtransaction=vtiger_accounting.accountingid
and
vtiger_accounting.accountingrelated2=vtiger_servicecontracts.servicecontractsid
and
vtiger_contactdetails.contactid=vtiger_servicecontracts.contactid and
vtiger_campaign.campaignid=cf_1155
and vtiger_crmentity.crmid=vtiger_servicecontracts.servicecontractsid
and vtiger_servicecontractscf.servicecontractsid=vtiger_servicecontracts.servicecontractsid

and accountingpaidamount=accountingamount

group by campaignname
having length(GROUP_CONCAT(accountingtype SEPARATOR " "))=12

我想要达到的目的是在上面的查询中显示列Kurang_Gesek的SUM结果..

有人可以帮忙吗?

先谢谢......

2 个答案:

答案 0 :(得分:1)

尝试使用子查询:

select sum(Kurang_Gesek)
from (<your query here>) q

答案 1 :(得分:0)

所以只需用另一个SELECT包装您的查询:

SELECT t. *, SUM(t.Kurang_Gesek)
FROM (
SELECT
...
UNION
...
) t
GROUP BY t.some_column_you_need