在MySQL中,可以在SELECT子句中创建的GROUP BY子句中使用别名(参见MySQL参考)。
我只是想知道为什么无法在GROUP BY中创建别名并在SELECT中使用它,该别名遵循SELECT语句的执行顺序。
换句话说,为什么以下语法不合语法?
SELECT region, SUM(population) FROM population_us_states GROUP BY CASE state_name WHEN 'CT' THEN 'New England' WHEN 'RI' THEN 'New England' WHEN 'MA' THEN 'New England' WHEN 'ME' THEN 'New England' WHEN 'NH' THEN 'New England' WHEN 'VT' THEN 'New England' WHEN 'CA' THEN 'West Coast' WHEN 'OR' THEN 'West Coast' WHEN 'WA' THEN 'West Coast' ELSE 'other' END AS region;
使用嵌套的SELECT-内部的一个提取总体并生成计算的列,然后外部的一个可以使用GROUP BY该列:
SELECT
GROUP BY
SELECT region, SUM(population) FROM ( SELECT CASE ... ... AS region, population FROM population_us_states ) GROUP BY region