为什么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 @   aspirant  阅读(4030)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
历史上的今天:
2019-04-03 FTP、FTPS和SFTP
2019-04-03 Spring自定义类扫描器 ClassPathScanningCandidateComponentProvider Spring生命周期 Constructor > @PostConstruct > InitializingBean > init-method
2019-04-03 Spring生命周期 Constructor > @PostConstruct > InitializingBean > init-method
2016-04-03 利用android来赚钱
点击右上角即可分享
微信分享提示