I have a sql select statement which contains some columns that are computed from some other columns or tables. I gave a name for this column using As keyword.
Now, I want to sort this table by the computed column. I cant use that name for sorting.
Someone please help to sort the sql table using computed column.
Sort Items Based on Host Variable Values Specify the ASC and DESC argument after the CASE END keyword. You must specify fields in a CASE expression by column name. Column aliases and column numbers are not permitted in this context.
Due to logical query processing order, alias can be used in order by.
You can use the alias in GROUP BY, ORDER BY, or HAVING clauses to refer to the column.
In ORDER BY you can refer to column aliases in the SELECT clause. This is what's happening in query 2. It isn't sorting by the values in the column.
In older versions of SQL Server, you can define the alias in a subquery:
select *
from (
select col1 + col2 as col3
from YourTable
) SubQueryAlias
order by
col3
In SQL Server 2008+ you should be able to order by
an alias without a subquery:
select col1 + col2 as col3
from YourTable
order by
col3
one more option you can use COLUMN INDEX NUMBER in order by as show in follwoing example
select ACol,AVal,CAST(ACol as varchar(3)) + aval as 'New' from ABC order by 3
this will use 'New' columnd to sort
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With