You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在SQL Server 2019中将两个SQL查询结果合并为单个结果集

解决方法

你可以直接用条件聚合实现需求,仅需一次查询即可得到目标结果,性能比分别查询再关联更优,适配SQL Server 2019 Express版本:

SELECT 
    s.SaleDate,
    SUM(s.SaleAmt) AS [Total Sales from All],
    SUM(CASE WHEN EXISTS (SELECT 1 FROM Customers c WHERE c.CustomerID = s.CustomerID) 
        THEN s.SaleAmt ELSE 0 END) AS [Total Sales from Customers]
FROM Sales s
GROUP BY s.SaleDate
ORDER BY s.SaleDate

如果你需要保留原有两个查询的逻辑进行合并,可以通过INNER JOIN关联两个子查询的结果:

SELECT 
    t1.SaleDate,
    t1.[Total Sales from All],
    t2.[Total Sales from Customers]
FROM 
(
    SELECT sales.saledate, SUM(sales.saleamt) AS [Total Sales from All] 
    FROM Sales 
    GROUP BY sales.saledate
) t1
INNER JOIN
(
    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
) t2 ON t1.SaleDate = t2.SaleDate
ORDER BY t1.SaleDate

两种写法都可以得到你预期的结果:

SaleDateTotal Sales from AllTotal Sales from Customers
11/1/2021900600
11/2/2021800700

内容的提问来源于stack exchange,提问作者TurboSonic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 11:15:03