如何从具有相同销售额的总和的两个不同表中获取数据?

问题描述 投票:1回答:3

我有以下两个表:

enter image description here

saleid是共同的专栏。我可以单独获得每个表的总数:

select saleid, sum(quantity) 
from table1
group by saleid;

select saleid, sum(extracted) 
from table2
group by saleid;

我需要将表2中提取的总和与每个销售的表1中的数量总和进行比较

我可以使用SQL Server或SQL的哪个工具来连接求和查询的输出并得到如下内容:

enter image description here

sql sql-server
3个回答
1
投票

使用内部联接和子查询尝试以下查询:

select a.saleid, quantity ,extracted from
(select saleid, sum(quantity) as quantity from table1 group by saleid)a
inner join
(select saleid, sum(extracted) as extracted from table2 group by saleid)b
on a.saleid=b.saleid
group by a.saleid

1
投票

假设两个表中的saleid相同,您可以将这两个表连接到列上,并通过以下查询获取数据

select t1.saleid, 
       sum(t1.quantity) , 
       sum(t2.extracted)
  from table1 t1 join table2 t2 
    on t1.saleid = t2.saleid
group by t1.saleid;

1
投票

试试这个 :

select t1.saleid, t1.quantitySum, t2.extractedSum from
(Select saleid, sum(quantity) as quantitySum from table1 group by saleid)t1 
inner join (Select saleid, sum(extracted) as extractedSum from table2 group by saleid)t2 on t1.saleid= t2.saleid and t1.quantitySum=t2.extractedSum ;
© www.soinside.com 2019 - 2024. All rights reserved.