SQL 服务器创建总计行

SQL Server create grand total row

我有一个包含订单详细信息的 table。如何在末尾创建一行来汇总我的所有小计?

SELECT 
    o.order_id, o.itemDescription as Description, 
    o.quantity_shipped as [Quantity], 
    o.itemCost as [Price each], 
    (o.quantity_shipped * CAST(o.itemCost as float)) as [Sub Total] 
FROM 
    dbo.order_items o

这将根据订单 ID 给出总计

SELECT o.order_id, SUM((o.quantity_shipped * CAST    (o.itemCost as float))) as [TotalByOrderId] 
    FROM   dbo.order_items o
    GROUP BY o.order_id

这将为您提供总计

SELECT SUM((o.quantity_shipped * CAST    (o.itemCost as float))) as [GrandTotal] 
FROM   dbo.order_items o

一种方式(不是最明智的方式)可以是以下方式:

;WITH CTE AS (
    SELECT o.order_id, o.itemDescription as Description, 
        o.quantity_shipped as [Quantity], 
        o.itemCost as [Price each], 
        (o.quantity_shipped * CAST(o.itemCost as float)) as [Sub Total] 
    FROM dbo.order_items o)
SELECT *
FROM CTE
UNION ALL
SELECT NULL, 'Grand Total', NULL, NULL, SUM([Sub Total])
FROM CTE

你为什么要这么做?添加一个无意义的合计行会让后面的处理复杂很多。除非你对子行进行分层汇总。

通常的处理方式是将总计作为发票的一部分 table。