Search code examples
sqlsql-servert-sqlsql-server-2000

T-SQL SUM Total


Below I have a T-SQL query that brings back amount of purchased items, less discounts and the total - grouped by month/year of purchase. How can I update the Query to return a Grand Total Row where I would can add up the amounts in the Total Column? It would be good to be able to add up all the rows but my main item is I need to be able to get a grand total. Thanks.

    Select DATENAME(month, [OrderDate]) + ' ' + CAST(YEAR(OrderDate) AS CHAR(4)) 
    AS [Month],
    SUM(Amount) AS [Amount],
    SUM(Discount1) AS [Discount 1],
    SUM(Discount2) AS [Discount 2],
    SUM(Amount - Discount1 - Discount2) AS [Total]
    From 
    Orders
    JOIN Customer on orders.cust_ky=customer.cust_ky
    GROUP BY DATENAME(month, [OrderDate]) + ' ' + CAST(YEAR(OrderDate) AS CHAR(4))
    ORDER BY MAX(OrderDate)

Solution

  • Depending on your version of sql-server, you might be able to implement the rollup function (SQL-Server 2005+):

    Select DATENAME(month, [OrderDate]) + ' ' + CAST(YEAR(OrderDate) AS CHAR(4)) AS [Month],
        SUM(Amount) AS [Amount],
        SUM(Discount1) AS [Discount 1],
        SUM(Discount2) AS [Discount 2],
        SUM(Amount - Discount1 - Discount2) AS [Total]
    From Orders
    JOIN Customer 
        on orders.cust_ky=customer.cust_ky
    GROUP BY ROLLUP(DATENAME(month, [OrderDate]) + ' ' + CAST(YEAR(OrderDate) AS CHAR(4)))
    ORDER BY MAX(OrderDate)
    

    Or you can use a UNION ALL similar to this, where the second query gets the total without the GROUP BY:

    Select DATENAME(month, [OrderDate]) + ' ' + CAST(YEAR(OrderDate) AS CHAR(4)) AS [Month],
        SUM(Amount) AS [Amount],
        SUM(Discount1) AS [Discount 1],
        SUM(Discount2) AS [Discount 2],
        SUM(Amount - Discount1 - Discount2) AS [Total]
    From Orders
    JOIN Customer 
        on orders.cust_ky=customer.cust_ky
    GROUP BY DATENAME(month, [OrderDate]) + ' ' + CAST(YEAR(OrderDate) AS CHAR(4))
    union all
    Select 'Total',
        SUM(Amount) AS [Amount],
        SUM(Discount1) AS [Discount 1],
        SUM(Discount2) AS [Discount 2],
        SUM(Amount - Discount1 - Discount2) AS [Total]
    From Orders
    JOIN Customer 
        on orders.cust_ky=customer.cust_ky