同事工做中遇到一个问题:mysql
select count(billingdate),to_char(billingdate,'YYYYmm') monthsql
from tu_tradeoracle
whereto_char(billingdate,'YYYY') =''and reportstat =
group by month;blog
-----执行报错,can't resolve month............get
由于Sql语句执行顺序it
(7)SELECTio
(8)DISTINCT table
(1)FROM date
(3) JOIN
(2)ON
(4)WHERE
(5)GROUP BY
(6)HAVING
(9)ORDER BY
(10)LIMIT
Group by不能用别名的缘由,由于执行到groupby(5)时,还没执行到select中的别名,因此别名还没生效。因此别名只能放到(7)以后,好比order中,distinct中。
遇到这种问题能够使用子查询替代
select month,count(month)
from
(selectcount(billingdate),to_char(billingdate,'YYYYmm') as month
from tu_trade
whereto_char(billingdate,'YYYY') =''and reportstat = 30) a
group by month;
注意:
在mysql中,group by中能够使用别名;where中不能使用别名;order by中能够使用别名。其他像oracle,hive中别名的使用都是严格遵循sql执行顺序的,groupby后面不能用别名。mysql特殊是由于mysql中对查询作了增强。
参考