来自 Union ALL SQL 的 SUM 或总结果

Posted

技术标签:

【中文标题】来自 Union ALL SQL 的 SUM 或总结果【英文标题】:SUM or Total results from Union ALL SQL 【发布时间】:2018-03-07 22:21:10 【问题描述】:

您好,我有查询要显示 2 个结果:

SELECT TOP (100) PERCENT CONVERT(varchar, GETDATE(), 103) AS Date, 
       'Sales Orders' AS Type, COUNT(SalesOrderID) AS Qty, 
       ISNULL(ROUND(SUM(SubTotal), 2),0) AS [Total Ex GST]
FROM  dbo.SalesOrder
WHERE  (DateCreated > CONVERT(int, GETDATE()-0.5))

UNION ALL

SELECT TOP (100) PERCENT CONVERT(varchar, GETDATE(), 103) AS Date,
       'Invoices', COUNT(InvoiceID) AS Qty, 
       ISNULL(ROUND(SUM(SubTotal),2),0) AS [Total Ex GST]
FROM         dbo.Invoice
WHERE  (DateCreated > CONVERT(int, GETDATE()-0.5)) 

如何添加这 2 个联合 55090.25 和 1522.8 来生成第三行?总计?

【问题讨论】:

你能告诉我们查询吗? 请编辑您的问题以添加它,以便您可以正确格式化它并且其他用户将能够看到它 @LioraHaydont 编辑它:) 为什么需要查询来计算总数?你不能在应用程序级别处理这个吗? @GiorgosBetsos 不幸的是没有,所以我需要显示一个自动报告,所以一旦我看到这两个值的结果,在第三行,我也可以看到这两个值的总和 :) 【参考方案1】:

这应该可行:

;WITH CTE
AS
(
    SELECT     TOP (100) PERCENT CONVERT(varchar, GETDATE(), 103) AS Date, 'Sales Orders' AS Type, COUNT(SalesOrderID) AS Qty, ISNULL(ROUND(SUM(SubTotal), 2),0) AS [Total Ex GST]
    FROM         dbo.SalesOrder
    WHERE     (DateCreated > CONVERT(int, GETDATE()-0.5))
    UNION
    SELECT     TOP (100) PERCENT CONVERT(varchar, GETDATE(), 103) AS Date, 'Invoices', COUNT(InvoiceID) AS Qty, ISNULL(ROUND(SUM(SubTotal), 2),0) AS [Total Ex GST]
    FROM         dbo.Invoice
    WHERE     (DateCreated > CONVERT(int, GETDATE()-0.5)) 
),
TotalCTE AS
(
    SELECT CONVERT(varchar, GETDATE(), 103) AS Date, 'Total' AS Type, SUM(Qty) AS Qty, SUM([Total Ex GST]) AS [Total Ex GST] FROM CTE
)
SELECT Date, [Type], Qty, [Total Ex GST] FROM CTE
UNION
SELECT Date, [Type], Qty, [Total Ex GST] FROM TotalCTE;

这是一个有效的小提琴: http://sqlfiddle.com/#!18/eb9a0/2/0

【讨论】:

【参考方案2】:

您的查询产生以下结果:

Date        Type          Qty  [Total Ex GST]
---------------------------------------------
2018-03-08  Sales Orders  100  55090.25  
2018-03-08  Invoices      200  1522.8

为了完整起见,我添加了一些任意的Qty 值。

您可以将查询包装在公用表表达式中,并对CTE 的结果集执行GROUP BY GROUPING SETS

;WITH CTE AS (
   ... your query here ...
)
SELECT [Date], 
       COALESCE(Type, 'Both') AS Type, 
       SUM(Qty) AS Qty, 
       Sum(Total) AS Total
FROM CTE
GROUP BY GROUPING SETS (([Date], Type),(Date))

Demo here

【讨论】:

以上是关于来自 Union ALL SQL 的 SUM 或总结果的主要内容,如果未能解决你的问题,请参考以下文章

sql union和union all

SQL - 使用 Union All 和 Join 计算

使用 UNION ALL 上一行结果的 SQL 表达式

如何简化mysql中的多个UNION ALL?

sql中union 和 union all的区别

sql 中union all有啥用法