为什么group by后面不能使用别名(除MySQL)

同事工作中遇到一个问题:

select   count(billingdate),to_char(billingdate,'YYYYmm') month

from tu_trade

where to_char(billingdate,'YYYY') ='2017'and reportstat = 30

group by month; 

-----执行报错,can't resolve month............

因为Sql语句执行顺序

(7)    SELECT

(8)    DISTINCT <select_list>

(1)    FROM <left_table>

(3)    <join_type> JOIN <right_table>

(2)    ON <join_condition>

(4)    WHERE <where_condition>

(5)    GROUP BY <group_by_list>

(6)    HAVING <having_condition>

(9)    ORDER BY <order_by_condition>

(10)   LIMIT <limit_number> 

Group by不能用别名的原因,因为执行到groupby(5)时,还没执行到select中的别名,所以别名还没生效。所以别名只能放到(7)之后,比如order中,distinct中。

遇到这种问题可以使用子查询替代

select month,count(month)

from

(selectcount(billingdate),to_char(billingdate,'YYYYmm')  as month

from tu_trade

where to_char(billingdate,'YYYY') ='2017'and reportstat = 30) a

group by month;

注意:
           在mysql中,group by中可以使用别名;where中不能使用别名;order by中可以使用别名。其余像oracle,hive中别名的使用都是严格遵循sql执行顺序的,groupby后面不能用别名。mysql特殊是因为mysql中对查询做了加强。

 

参考:为什么group by后面不能使用别名(除MySQL)

posted @ 2020-04-03 14:14  aspirant  阅读(3939)  评论(0编辑  收藏  举报