I've got a problem with my order by clause when using a calculated column with an alias as below:
This order by works without any problem
declare @Mode int = 1
declare @Sort nvarchar(max) = 'engname'
select top 10 School.Id as EntityId,
School.EnglishName as EntityEnglishName,
School.Name as EntityNativeName,
case
when @Mode = 0 then 0
when @Mode = 1 then 1
when @Mode = 2 then 2
end as ActiveStudents
from V_SchoolMinimized as School
Order By ActiveStudents
The following query has an error:
Invalid column name 'ActiveStudents'
declare @Mode int = 1
declare @Sort nvarchar(max) = 'engname'
select top 10 School.Id as EntityId,
School.EnglishName as EntityEnglishName,
School.Name as EntityNativeName,
case
when @Mode = 0 then 0
when @Mode = 1 then 1
when @Mode = 2 then 2
end as ActiveStudents
from V_SchoolMinimized as School
Order By
case when @Sort is null then School.Id end,
case when @Sort = 'engname' then ActiveStudents end
How can I use ActiveStudents within the conditional order by clause as shown?