来自两个不同查询的求和结果(SQL)

时间:2017-08-28 16:05:34

标签: sql sql-server

我有来自两个不同表的两个查询。一个使用SUM函数,另一个使用COUNT函数。我需要的是总结他们的结果,这样我就可以得到一个包含总记录的表格(例如Table" C")。

到目前为止,我已尝试过此次加入,但它无效:

$> PORT=8000 node app.js

表A(已收到联系人)

select a.origin, count(*) as received, sum(b.contacts) as sent
from bd.received a 
left join db.sent b
on a.origin=b.origin
group by b.origin 

表B(已发送联系人)

select count(*), origin from db.received group by origin

   Origin Count(*)
   Email    500
   Phone    200 
   Social   100

表C(总联系人)

select sum(contacts), origin from db.sent group by origin

   Origin Sum(*)
   Email    20
   Phone   100

3 个答案:

答案 0 :(得分:6)

您可以union all在派生表/子查询中对每个计​​数查询进行select origin , Received = sum(ReceivedCount) , Sent = sum(SentCount) , Total = sum(ReceivedCount)+sum(SentCount) from ( select origin, ReceivedCount = count(*), SentCount=0 from bd.received group by origin union all select origin, ReceivedCount = 0, SentCount=count(*) from db.sent group by origin ) s group by origin ,如下所示:

 let browser = window.open('https://www.payumoney.com/paybypayumoney/#/abcd1234', '_self');
     browser.addEventListener('loadstart',function(event){
      console.log(event)
      if (event["url"] == "http://localhost:3000/capture_successfull_payment") {
         browser.close()
        }
       });

答案 1 :(得分:0)

您可以使用以下查询 -

select t1.origin , sum(received) from 
(
select a.origin, count(*) received 
from db.received a 
group by a.origin 
union all
select b.origin, count(*) sent 
from db.sent b 
group by b.origin 
) as t1 
group by t1.origin

答案 2 :(得分:0)

这应该做的工作

select origin,
       sum(count) 
from (
      select * from rec 
      union all
      select * from  sent) 
group by  
origin

这里的链接 http://www.sqlfiddle.com/#!4/0a8fc/1