0

下面我有一个 T-SQL 查询,它带回购买商品的数量、折扣和总数——按购买的月/年分组。如何更新查询以返回总计行,我可以将总计列中的金额相加?能够将所有行加起来会很好,但我的主要项目是我需要能够获得总计。谢谢。

    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)
4

1 回答 1

6

根据您的 sql-server 版本,您可能能够实现汇总功能(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)

或者您可以使用UNION ALL与此类似的方法,其中第二个查询获取总数而没有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
于 2012-10-25T20:49:37.030 回答