[Turn] Why can not group by using an alias later (except MySQL)

Work colleagues encountered a problem:

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

from tu_trade

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

group by month; 

----- execution error, can not resolve month ............

Because the execution order Sql statement

(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 reason alias can not be used, because the execution groupby (5), not performing to select the alias, the alias not take effect. So after only put an alias (7), in such order, distinct in.

Encounter this problem you can use subqueries alternative

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;

Note:
           in mysql, group by the alias can be used; WHERE can not use aliases; order by the alias can be used. Like the rest of oracle, hive used aliases are strictly follow the sql execution order, groupby behind can not use an alias. mysql special because mysql query made in strengthening.

reference

https://blog.csdn.net/qq_26442553/article/details/80867076

Guess you like

Origin www.cnblogs.com/DarrenChan/p/11634750.html