我有一个带有两列的sql Log表,如下所示:
RegistrantID compnayID Creation date
1 1 .....
1 1
2 1
3 1
1 2
2 2
2 2
3 2 .....
我有一个存储过程,它带来了第一个基于记录的创建日期。如果两家公司具有相同的注册人ID,那么它会带来一个记录,因此对于注册1,它将是第一行而不是第5行,而对于注册人ID 2,它将带来第3行但不是第6行。我希望第1行和第5行为注册表1,第3和第6行为注册人2,第4行和第8行为注册人ID 3.这是我的存储过程。
ALTER PROCEDURE [dbo].[hr_ActionLog_GetList]
@Action INT = NULL,
@DateFrom DATETIME = NULL,
@DateTo DATETIME = NULL,
@CompanyID INT = NULL,
@RegistrantID INT = NULL,
@VacancyID INT = NULL,
@Language INT = 1
AS
BEGIN
WITH CTE AS
(
SELECT AL.*,
RV.Forename,
RV.Surname,
RV.Username AS RegistrantUsername,
E.Forename AS EmployeeForename,
E.Surname AS EmployeeSurname,
U.Username,
CASE
WHEN @Language = 2 THEN C.NameLang2
ELSE C.NameLang1
END AS CompanyName,
CASE
WHEN @Language = 2 THEN V.JobTitleLang2
ELSE V.JobTitleLang1
END AS JobTitle
, ROW_NUMBER() OVER(PARTITION BY AL.RegistrantID
ORDER BY ActionDate ASC) AS RN
FROM dbo.hr_ActionLog AL LEFT OUTER JOIN dbo.RegistrantsListView RV ON AL.RegistrantID = RV.RegistrantID
LEFT OUTER JOIN dbo.hr_Employees E ON AL.EmployeeID = E.EmployeeID
LEFT OUTER JOIN dbo.hr_Users U ON AL.UserID = U.UserID
LEFT OUTER JOIN dbo.hr_Companies C ON AL.CompanyID = C.CompanyID
LEFT OUTER JOIN dbo.hr_Vacancies V ON AL.VacancyID = V.VacancyID
LEFT OUTER JOIN dbo.hr_Companies VC ON V.CompanyID = VC.CompanyID
WHERE (@Action IS NULL OR AL.Action = @Action)
AND (@DateFrom IS NULL OR dbo.DateOnly(AL.ActionDate) >= dbo.DateOnly(@DateFrom))
AND (@DateTo IS NULL OR dbo.DateOnly(AL.ActionDate) <= dbo.DateOnly(@DateTo))
AND (@CompanyID IS NULL OR AL.CompanyID = @CompanyID)
AND (@RegistrantID IS NULL OR AL.RegistrantID = @RegistrantID)
AND (@VacancyID IS NULL OR AL.VacancyID = @VacancyID)
--ORDER BY AL.ActionDate DESC
)
SELECT *
FROM CTE
WHERE RN = 1;
END
请建议如何更改此存储过程?
答案 0 :(得分:4)
您需要按RegistrantId和CompanyID进行分区
ROW_NUMBER() OVER(PARTITION BY AL.RegistrantID, AL.CompanyID
ORDER BY ActionDate ASC)
答案 1 :(得分:0)
删除where子句RN = 1并添加distinct应该就足够了。