同事工作中遇到一个问题:
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
;