如何在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
两种写法都可以得到你预期的结果:
| SaleDate | Total Sales from All | Total Sales from Customers |
|---|---|---|
| 11/1/2021 | 900 | 600 |
| 11/2/2021 | 800 | 700 |
内容的提问来源于stack exchange,提问作者TurboSonic
相关产品推荐
相关产品推荐

