将两个SQL语句与sum结合使用

时间:2018-01-18 19:34:33

标签: sql

两个陈述需要结合起来。

select INVOICEAMOUNT, itemid 
from MTS_NONPAYMENT

select SUM(AMOUNT) AS SUM, ITEMID 
from CUS_GLACCOUNT 

公共专栏itemid。每次我尝试加入时,都会失败。我做错了什么?

1 个答案:

答案 0 :(得分:2)

从根本上说,您似乎缺少group by。我怀疑以下是你想要的:

select itemid, sum(invoiceamount) as invoiceamount, sum(sum) as sum
from ((select itemid, sum(INVOICEAMOUNT) as invoiceamount, 0 as sum
       from MTS_NONPAYMENT
       group by itemid
      ) union all
      (select itemid, 0, SUM(AMOUNT)
       from CUS_GLACCOUNT 
       group by itemid
      ) 
     ) x
group by itemid;

要获得不相等的值,请使用:

having sum(invoiceamount) <> sum(sum) 

在查询结束时。