Search code examples
sql-serversubtotal

SQL Server create grand total row


I have a table that contains order details. How can I create a row at the end that totals all my subtotals?

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

Solution

  • This will give you total by Order 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
    

    This will give you grand total

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