我的桌子上有3名员工。我正在使用此存储过程尝试遍历并显示每个员工的数据。但是,它将为第一个员工返回3x的数据,而对于其他两个员工则不返回任何数据。如果我从表中删除一个雇员,那么我将有2个雇员,它将返回第一个雇员2x的数据。
USE [Payroll]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[EmployeeProfitability]
@PayrollDate DATETIME
AS
BEGIN
SELECT
0 AS Id, FirstName, LastName
FROM
dbo.Employees e
LEFT JOIN
(SELECT
EmployeeId
FROM
dbo.EmployeeJobs ej
WHERE
PayrollDate = @PayrollDate
GROUP BY
ej.EmployeeId) AS Volume ON e.EmployeeId = Volume.EmployeeId
END
我得到的回报是
Bob Saget
Bob Saget
Bob Saget
我正在尝试
Bob Saget
Ron Swanson
Dwayne Johnson
答案 0 :(得分:0)
由ID,名字,姓氏导致选择中出现重复行的原因。当您尝试使用具有group by子句的表进行左联接时,您需要关心select的第一条语句。
SELECT 0 AS e.empoloyeeId, e.FirstName, e.LastName,
Volume.Volume AS Volume,
Volume.MaterialPct AS MaterialPct,
Volume.LaborPct AS LaborPct,
Volume.ProfitPct AS ProfitPct,
Volume.Systems AS Systems,
Volume.AOR AS AOR,
Volume.Upgrade AS Upgrade,
Volume.Condemned AS Condemned,
Volume.TravelTime AS TravelTime,
Volume.RegularHours AS RegularHours,
Volume.OvertimeHours AS OvertimeHours
from dbo.Employees e
LEFT JOIN (
SELECT EmployeeId,
SUM(Billing) AS Volume,
SUM(Billing) / SUM(MaterialCost) AS MaterialPct,
SUM(Billing) / SUM(Pay) AS LaborPct,
SUM(Billing) / SUM(Profit) AS ProfitPct,
SUM(System) AS Systems,
SUM(AOR) AS AOR,
SUM(Upgrade) AS Upgrade,
SUM(Condemned) AS Condemned,
SUM(TravelMinutes) AS TravelTime,
SUM(RegularHours) AS RegularHours,
SUM(OvertimeHours) AS OvertimeHours
FROM dbo.EmployeeJobs ej
WHERE PayrollDate = @PayrollDate
GROUP BY ej.EmployeeId
) AS Volume ON
e.EmployeeId = Volume.EmployeeId
group by e.empoloyeeId, e.FirstName, e.LastName
希望这项工作对您有用。