Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
452 views
in Technique[技术] by (71.8m points)

sql - Why can't I use an alias for an aggregate in a having clause?

My code is like shown below :

select col1,count(col2) as col7
from --some join operation
group by col1
having col7 >= 3 -- replace col7 by count(col2) to make the code work

My code causes the error "Invalid column name 'col7' ". Why does this happen ? It seems illogical that SQL does not allow me to use col7 in the last line.

I am using SQL server express 2008

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The HAVING clause is evaluated before the SELECT - so the server doesn't yet know about that alias.

  1. First, the product of all tables in the FROM clause is formed.

  2. The WHERE clause is then evaluated to eliminate rows that do not satisfy the search_condition.

  3. Next, the rows are grouped using the columns in the GROUP BY clause.

  4. Then, groups that do not satisfy the search_condition in the HAVING clause are eliminated.

  5. Next, the expressions in the SELECT statement target list are evaluated.

  6. If the DISTINCT keyword in present in the select clause, duplicate rows are now eliminated.

  7. The UNION is taken after each sub-select is evaluated.

  8. Finally, the resulting rows are sorted according to the columns specified in the ORDER BY clause.

  9. TOP clause is executed.

Hope this answers your question. Also, it explains why the alias works in ORDER BY clause.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...