Leaving an alias in a group by statement

时间:2017-08-04 13:01:52

标签: sql sql-server group-by

From time to time if I have used a case statement in my select, and then copy this into the group by, I leave the alias in by mistake.
The alias is essentially superfluous at this point, and is not allowed as it is incorrect syntax.
Why is this not allowed as I cannot see that it affects the overall output? Is it simply a design choice?

1 个答案:

答案 0 :(得分:0)

这是因为GROUP BY首先在SELECT之前执行,因此尚未定义别名,因此SQL还不知道它。这样,您就可以在ORDER BY中使用别名。

请参阅

下面的SQL执行层次结构
  1. FROM
  2. ON
  3. OUTER
  4. WHERE
  5. GROUP BY
  6. CUBE | ROLLUP
  7. HAVING
  8. 选择
  9. DISTINCT
  10. ORDER BY
  11. TOP