我想添加一行并添加总和列的值。 。参见下面的代码。 谢谢
` 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`
答案 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