Ordering the results of CTE in SQL
I have following SQL:
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 VC.CompanyID IS NULL THEN
CASE
WHEN @Language = 2 THEN V.CompanyNameLang2
ELSE V.CompanyNameLang1
END
ELSE
CASE
WHEN @Language = 2 THEN VC.NameLang2
ELSE VC.NameLang1
END
END AS VacancyCompanyName,
CASE
WHEN @Language = 2 THEN V.JobTitleLang2
ELSE V.JobTitleLang1
END AS JobTitle
, ROW_NUMBER() OVER(PARTITION BY AL.RegistrantID, AL.CompanyID
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;
It returns first element from the group based on actiondate which is fine
but the returned result is not ordered by date means returns each groups
first record but the this collection of first records is not ordered by
action date. I tried ORDER BY AL.ActionDate DESC in CTE but it gives
error:
The ORDER BY clause is invalid in views, inline functions, derived tables,
subqueries, and common table expressions, unless TOP or FOR XML is also
specified.
No comments:
Post a Comment