0

我有一个带有两列的 sql 日志表,如下所示:

RegistrantID   compnayID  Creation date

1                1          .....
1                1             
2                1
3                1
1                2
2                2
2                2
3                2          .....

我有一个存储过程,它带来了第一个基于记录的创建日期。如果两个公司具有相同的注册人 ID,则它会带来一条记录,因此对于 registrantid 1,它将是第一行而不是第 5 行,对于 registrantId 2,它将带来第 3 行而不是第 6 行。我想为 registrantid 1 获取第 1 行和第 5 行,为 registrantid 2 获取第 3 行和第 6 行,为 registrant id 3 获取第 4 行和第 8 行。这是我的存储过程。

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

请建议如何更改此存储过程?

4

2 回答 2

4

您需要同时按 RegistrantId 和 CompanyID 进行分区

ROW_NUMBER() OVER(PARTITION BY AL.RegistrantID, AL.CompanyID 
                  ORDER BY ActionDate ASC)
于 2013-08-16T05:57:00.113 回答
0

删除 where 子句 RN=1 并添加 distinct 就足够了。

于 2013-08-16T05:50:21.993 回答