I've got Sql Server Query like this:
Select *
,Cast(Column1 as float) as Column1Convert
,Cast(Column2 as float) as Column2Convert
,Column1Convert/Colun2Convert AS [Result]
From MyTable
Order By Points DESC, Result ASC
But I'am receiving error: "Invalid column name 'Column1Convert'." and second error: "Invalid column name 'Column2Convert'."
Could You tell me what I'am doing wrong ?
This is because you are using aliases in the same level of the query which is not allowed. Try:
Select *
,Cast(Column1 as float) as Column1Convert
,Cast(Column2 as float) as Column2Convert
,Cast(Column1 as float)/Cast(Column2 as float) AS [Result]
From MyTable
Order By Points DESC, Result ASC
Try this:
SELECT
Points, Result, Column1Convert, Column2Convert,
Column1Convert/Colun2Convert AS [Result]
FROM
(
Select *
,Cast(Column1 as float) as Column1Convert
,Cast(Column2 as float) as Column2Convert
From MyTable
)
Order By
Points DESC,
(Column1Convert/Colun2Convert) ASC
In SQL Server there is another way to access field aliases for reuse (aside from nested query)
SELECT
Points
, ca.Column1Convert
, ca.Column2Convert
, ca.Column1Convert / ca.Colun2Convert AS [Result]
FROM MyTable
CROSS APPLY (
SELECT
CAST(Column1 AS float) AS Column1Convert
, CAST(Column2 AS float) AS Column2Convert
) AS ca
ORDER BY
Points DESC
, [Result] ASC
If available to you, you may want to use TRY_CAST() instead of CAST()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.