通过在Sql Server中划分两个数字来排序查询

时间:2014-08-19 09:49:54

标签: sql sql-server

我有这样的Sql Server查询:

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

但我收到错误:"列名无效' Column1Convert'。"和第二个错误:"列名无效' Column2Convert'。"

你能告诉我我做错了什么吗?

3 个答案:

答案 0 :(得分:3)

这是因为您在查询的同一级别使用别名,这是不允许的。  尝试:

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

答案 1 :(得分:1)

试试这个:

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

答案 2 :(得分:1)

在SQL Server中,还有另一种方法可以访问字段别名以供重用(除了嵌套查询)

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

如果您可以使用,则可能需要使用TRY_CAST()而不是CAST()