您好我已經寫了查詢下面的問題,我的問題是顯然返回整個表的總和(所有員工在一起),我希望它返回每個員工的總和,這完全有可能嗎?獲取每個SQL行的總和
DECLARE @temp TABLE
(
TotalAmount DECIMAL,
ExpenseCategory UNIQUEIDENTIFIER,
EmployeeId UNIQUEIDENTIFIER,
CategoryName NVARCHAR(100)
)
INSERT INTO @temp
SELECT SUM(dbo.ExpenseDetails.TotalAmount) AS TotalAmount,
dbo.ExpenseDetails.ExpenseCategory, dbo.ExpenseDetails.EmployeeId,
dbo.ExpensesCategories.CategoryName
FROM dbo.ExpenseDetails INNER JOIN
dbo.ExpensesCategories ON
dbo.ExpenseDetails.ExpenseCategory = dbo.ExpensesCategories.CategoryId
WHERE (CONVERT(DATE, dbo.ExpenseDetails.DateAdded) < CONVERT(DATE,
DATEADD(m, DATEDIFF(m, 0, CONVERT(DATE, GETDATE())), 23 - 1))) AND
(CONVERT(DATE, dbo.ExpenseDetails.DateAdded) > CONVERT(DATE,
DATEADD(MONTH, - 1, DATEADD(m, DATEDIFF(m, 0,
CONVERT(DATE, GETDATE())), 23 - 1))))
GROUP BY dbo.ExpenseDetails.ExpenseCategory, dbo.ExpenseDetails.EmployeeId,
dbo.ExpensesCategories.CategoryName
SELECT
EmployeeId,
(SELECT SUM(TotalAmount) FROM @temp WHERE EmployeeId = [@temp].EmployeeId
and ExpenseCategory = '6CC0F801-D295-4997-9D1F-3E5B2BE692ED') AS TotalFuel,
(SELECT SUM(TotalAmount) FROM @temp WHERE EmployeeId = [@temp].EmployeeId
and ExpenseCategory = '3E54C10B-ECBE-4B28-87A4-5A4E43AACDFC') AS TotalRail,
(SELECT SUM(TotalAmount) FROM @temp WHERE EmployeeId = [@temp].EmployeeId
and ExpenseCategory = '31CC43A4-80E6-4DD4-A28C-039F05AF62A3') AS
TotalParking,
(SELECT SUM(TotalAmount) FROM @temp WHERE EmployeeId = [@temp].EmployeeId
and ExpenseCategory = '01250A30-3865-40D2-9E49-DA2B9898B1F4') AS
TotalMileage,
(SELECT SUM(TotalAmount) FROM @temp WHERE EmployeeId = [@temp].EmployeeId
and ExpenseCategory = 'F4E4582D-DEDF-499D-BBC1-45003B865218') AS TotalEquip,
(SELECT SUM(TotalAmount) FROM @temp WHERE EmployeeId = [@temp].EmployeeId
and ExpenseCategory = '55F471C1-6E52-4898-8263-0B7684B78E7C') AS TotalPPS,
(SELECT SUM(TotalAmount) FROM @temp WHERE EmployeeId = [@temp].EmployeeId
and ExpenseCategory = '1EE0FC40-193F-4720-9143-0B61FFDE7B8D') AS TotalOther
FROM @temp GROUP BY EmployeeId
米哈伊爾·你好,這工作得很好,唯一的問題是現在,它不會讓我組由僱員,所以我結束了重複行。 –
我錯過了。隨着'組',你不需要'OVER' –
乾杯米哈伊爾,偉大的工程! –