Restrictions on directly using column aliases for calculations in SQL queries
In the given SQL query, trying to use the column aliases ROUND(avg_time * cnt, 2)
and avg_time
in the expression cnt
results in the error "Column 'avg_time' does not exist".
The root cause lies in the order of evaluation of the SELECT
statements. The program processes the entire SELECT
statement simultaneously, so the alias value cannot be recognized at that point in time.
Solution: Use nested subqueries
To solve this problem, the query can be encapsulated using a subquery, effectively creating an intermediate data set. In this subquery, you can create the required column aliases avg_time
and cnt
.
<code class="language-sql">SELECT stddev_time, max_time, avg_time, min_time, cnt, ROUND(avg_time * cnt, 2) as slowdown FROM ( SELECT COALESCE(ROUND(stddev_samp(time), 2), 0) as stddev_time, MAX(time) as max_time, ROUND(AVG(time), 2) as avg_time, MIN(time) as min_time, COUNT(path) as cnt, path FROM loadtime GROUP BY path ORDER BY avg_time DESC LIMIT 10 ) X;</code>
Now, when executing this query, the subquery is evaluated first, producing a dataset containing the required column aliases. Subsequent SELECT
statements can then successfully reference these aliases.
The above is the detailed content of Why Can't I Use Column Aliases Directly in the Same SELECT Statement's Calculations?. For more information, please follow other related articles on the PHP Chinese website!