zoukankan      html  css  js  c++  java
  • 为什么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)

  • 相关阅读:
    A1039 Course List for Student (25 分)
    A1101 Quick Sort (25 分)
    日常笔记6C++标准模板库(STL)用法介绍实例
    A1093 Count PAT's (25 分)
    A1029 Median (25 分)
    A1089 Insert or Merge (25 分)
    A1044 Shopping in Mars (25 分)
    js 验证
    根据string获取对应类型的对应属性
    HTML 只能输入数字
  • 原文地址:https://www.cnblogs.com/aspirant/p/12626203.html
Copyright © 2011-2022 走看看