同事工作中遇到一個問題:
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中對查詢做了加強。