将多个 SQL 查询组合成单个结果

Posted

技术标签:

【中文标题】将多个 SQL 查询组合成单个结果【英文标题】:Combine multiple SQL queries into single result 【发布时间】:2021-11-25 04:50:11 【问题描述】:

我正在尝试将 2 个查询的结果放入一个结果集中。我正在使用 SQL Server 2019 Express。

这是我正在处理的数据:

Sales

SaleDate SaleAmt CustomerID
11/1/2021 500 123
11/1/2021 100 234
11/1/2021 300 345
11/2/2021 500 456
11/2/2021 100 567
11/2/2021 200 678

Customers

CustomerID CustomerName
123 Jon Doe
234 Jane Doe
456 Bob Doe
678 Jim Doe

查询 #1:

select sales.saledate, sum(sales.saleamt) as 'Total Sales from All' 
from Sales 
group by sales.saledate

查询 #2:

select sales.saledate, sum(sales.saleamt) as 'Total Sales from Customers'
from Sales 
where sales.customerid in (select customerid from customers) 
group by sales.saledate

这是我想要的结果:

SaleDate Total Sales from All Total Sales from Customers
11/1/2021 900 600
11/2/2021 800 700

【问题讨论】:

【参考方案1】:

您可以在销售日期使用加入

select s1.saledate, All_Total AS 'Total Sales from All', CustomersTotal as 'Total Sales from Customers'
from (
         select sales.saledate, sum(sales.saleamt) as All_Total
         from Sales
         group by sales.saledate
     ) s1
         inner join
     (
         select sales.saledate, sum(sales.saleamt) as CustomersTotal
         from Sales
         where sales.customerid in (select customerid from customers)
         group by sales.saledate
     ) s2 on s1.saledate = s2.saledate

【讨论】:

【参考方案2】:

您可以使用case 表达式将其组合在一个查询中。

select s.saledate, 
       sum(s.saleamt) as [Total Sales from All],
       sum(case when exists 
                     (
                         select * 
                         from   customers c 
                         where  c.customerid = s.customerid 
                     ) 
                then s.salesamt 
                end) as [Total Sales from Customers]
from   Sales s
group by s.saledate

【讨论】:

【参考方案3】:

您可以将LEFT JOIN 与条件聚合一起使用

select
  s.saledate,
  sum(s.saleamt) as [Total Sales from All],
  sum(case when c.customerid is not null then s.saleamt end) as [Total Sales from Customers]
from Sales s
left join customers c on s.customerid = c.customerid
group by s.saledate;

【讨论】:

以上是关于将多个 SQL 查询组合成单个结果的主要内容,如果未能解决你的问题,请参考以下文章

组合查询

如何将 4 个 sql 查询组合成一个性能良好的查询?

将多个mysql查询组合成一个结果

第十七章 组合查询

组合查询

组合查询