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

Posted

技术标签:

【中文标题】对两个不同查询 (SQL) 的结果求和【英文标题】:Sum results from two different queries (SQL) 【发布时间】:2017-08-28 16:05:33 【问题描述】:

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

到目前为止,我已经尝试过这种加入,但它不起作用:

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 

表 A(收到的联系人)

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

   Origin Count(*)
   Email    500
   Phone    200 
   Social   100

表 B(已发送联系人)

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

   Origin Sum(*)
   Email    20
   Phone   100

表 C(联系人总数)

   Origin Total
   Email   520
   Phone   300
   Social  100

【问题讨论】:

UNION ALL 查询,然后是 GROUP BY OriginSUM(Total) 【参考方案1】:

您可以像这样在派生表/子查询中 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

【讨论】:

@PaulaC 乐于助人!【参考方案2】:

您可以使用以下查询 -

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

【讨论】:

【参考方案3】:

这应该可以完成工作

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

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

【讨论】:

以上是关于对两个不同查询 (SQL) 的结果求和的主要内容,如果未能解决你的问题,请参考以下文章

sql对查询结果求和

sql实现多字段求和并查询

SQL Pivot 未对所有结果求和

如何在 MySQL 中对两个结果集中的列求和

如何对两列求和并通过减去它们的聚合 SQL 和 C# 在第三列中显示结果?

Informix SQL 查询:返回不同结果的两个相似查询