Why can’t I group by “cnt” and have to group by count(*). This just seems redundant and I wish there was a better way.
SELECT count(*) as cnt
from table
group by count(*)
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
It has to do with the logical processing order of SQL queries. Specifically, the GROUP BY clause is evaluated before the SELECT clause, despite appearing at the bottom of the query. Hence, aliases used in the SELECT are not necessarily available to the query processor while it evaluates the logically-precedent parts of the query.
Same reason you can’t use aliases in a WHERE clause: that clause is logically processed before the SELECT. ORDER BY, on the other hand, is the last part of the query to be processed – aliases (or even ordinal column positions) are typically supported there.
Some implementations may choose to provide this support – see the MySQL link that @daghan posted, for example – but it cannot be relied on; SQL Server, as you can see, doesn’t support it.
It’s worth pointing out that, were you desperate to refer to a complex expression by an alias, you could perhaps put that expression in a subquery, and refer to it from there. I’d call that overkill in most simple scenarios, though (such as the one in your question).
Update: @MartinSmith raises a good point in his comment on the question: aliasing aside, grouping by an aggregate expression isn’t going to work. In fact, since the aggregate is determined by a grouping of non-aggregate columns, it doesn’t even really make sense. What are you actually trying to achieve with such a query? Perhaps we can help further.