Sort Sql Table Using Alias ​​Column

I have a select sql statement that contains some columns that are computed from other columns or tables. I gave a name for this column using the As keyword.

Now I want to sort this table by computed column. I cannot use this name to sort.

Someone please help sort sql table using computed column

+6
source share
2 answers

another option, you can use the QUANTITY INDEX NUMBER in the order as shown in the following example

select ACol,AVal,CAST(ACol as varchar(3)) + aval as 'New' from ABC order by 3 

this will use the "New" column d to sort

+5
source

In older versions of SQL Server, you can define an alias in the subquery:

 select * from ( select col1 + col2 as col3 from YourTable ) SubQueryAlias order by col3 

In SQL Server 2008+, you must have order by alias without a subquery:

 select col1 + col2 as col3 from YourTable order by col3 
+15
source

Source: https://habr.com/ru/post/944362/


All Articles