获取SQL Server 2012中的Sum列的总和

时间:2018-07-12 06:39:01

标签: sql-server-2012

我想添加一行并添加总和列的值。 。参见下面的代码。 谢谢

` SELECT 
             TicketSales.DeviceID AS [Device ID]
            ,COUNT(TicketSales.TicketID) AS [Total Issued Tickets]
            ,SUM(TicketSales.TotalPrice) AS [Total Amount]

            (Here I want to add row to get the sum of SUM(TicketSales.TotalPrice) As [Total Amount])

           FROM dbo.TicketSales
           WHERE CONVERT(VARCHAR, TicketSales.StartTime,101) BETWEEN '" & fromDate & "' AND '" & toDate & "'
           GROUP BY TicketSales.DeviceID`

1 个答案:

答案 0 :(得分:0)

尝试使用窗口SUM()SUM()中的实际GROUP BY

SELECT 
    TicketSales.DeviceID AS [Device ID]
    ,COUNT(TicketSales.TicketID) AS [Total Issued Tickets]
    ,SUM(TicketSales.TotalPrice) AS [Total Amount]
    ,SUM(SUM(TicketSales.TotalPrice)) OVER()
FROM dbo.TicketSales
WHERE CONVERT(VARCHAR, TicketSales.StartTime,101) BETWEEN '" & fromDate & "' AND '" & toDate & "'
GROUP BY TicketSales.DeviceID`

OVER()子句使最外面的SUM()成为窗口加和,因此可以将其与分组的列或汇总结果一起使用。


编辑:如果您希望将其连续显示,则需要UNION

;WITH Aggregates AS
(
    SELECT 
        TicketSales.DeviceID AS [Device ID]
        ,COUNT(TicketSales.TicketID) AS [Total Issued Tickets]
        ,SUM(TicketSales.TotalPrice) AS [Total Amount]
    FROM dbo.TicketSales
    WHERE CONVERT(VARCHAR, TicketSales.StartTime,101) BETWEEN '" & fromDate & "' AND '" & toDate & "'
    GROUP BY TicketSales.DeviceID`
)
SELECT
    A.[Device ID],
    A.[Total Issued Tickets],
    A.[Total Amount]
FROM
    Aggregates AS A
UNION ALL
SELECT
    [Device ID] = NULL,
    [Total Issued Tickets] = SUM(A.[Total Issued Tickets]),
    [Total Amount] = SUM(A.[Total Amount])
FROM
    Aggregates AS A