I want my sql statement to use order by clause using Case Statement
and the column in used in order by is a computed column, for example:
declare @pOrderBy int
set @pOrderBy=1
Select ArtistId as Counting, ROW_NUMBER() OVER (ORDER BY
CASE WHEN (@pOrderBy = 1) THEN "Counting" end)
from master.dbo.Album
I got the error
Invalid column name 'Counting'.
I want to mention here that in actual query my Counting column is a computed column like:
Count(*) as Counting
You can’t reuse the column alias at the same level as it is defined.
In this case I would just use
ORDER BY ArtistIdrather than trying to reuse the alias. For more complicated expressions you might consider defining it in a CTE or aCROSS APPLYas discussed in this article.