Why can't I use column aliases in the next SELECT expression?

前端 未结 4 830
别跟我提以往
别跟我提以往 2020-11-28 16:18

Can I modify the next to use the column aliases avg_time and cnt in an expression ROUND(avg_time * cnt, 2)?

SELECT 
           


        
4条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-28 16:29

    The order of execution of a query (and thus the evaluation of expressions and aliases) is NOT the same as the way it is written. The "general" position is that the clauses are evaluated in this sequence:

    FROM
    WHERE
    GROUP BY
    HAVING
    SELECT
    ORDER BY
    

    Hence the column aliases are unknown to most of the query until the select clause is complete (and this is why you can use aliases in the ORDER BY clause). However table aliases which are established in the from clause are understood in the where to order by clauses.

    The most common workaround is to encapsulate your query into a "derived table"

    Suggested reading: Order Of Execution of the SQL query

    Note: different SQL dbms have different specific rules regarding use of aliases

    EDIT The purpose behind reminding readers of the logical clause sequence is that often (but not always) aliases only becomes referable AFTER the clause where the alias is declared. The most common of which is that aliases declared in the SELECT clause can be used by the ORDER BY clause. In particular, an alias declared in a SELECT clause cannot be referenced within the same SELECT clause.

    But please do note that due to differences in products not every dbms will behave in this manner

提交回复
热议问题