【hive】where使用注意的问题

不能再where后边使用别名,group by后边也一样不能使用别名

select id,col1 - col2 from table1

where (col1 - col2) > 1000;  —可以运行,但是不是很好看

尝试

select id,(col1 - col2) as n1 from table1

where n1 > 1000;   —会报错,因为where后边不能使用别名

如果筛选条件是个算式而且很长,总不能直接搬上吧

如何解决呢?

使用嵌套select

为什么where group by后边不能用别名呢?(mysql中group by后边可以用别名)

因为别名执行依附于select,而select的执行在where group by之后

所以不能用,在select执行操作后边的操作可以用,比如order by limit等.

下面是执行顺序

 (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> 

我们发现select在第7位,where group by having 都是在select前面的,所以不能用别名.

注意:在使用where的时候后边加的过滤字段不能是非聚合字段,而having后边加的是聚合字段

   因为where执行的顺序是在group by之前,所以不能用聚合字段

   where 和 having 可以同时使用,一个作用非聚合字段,一个作用聚合字段.

select t.id, t.n1 from(

select id,(col1 -col2) as n1 from table1

) e

where e.n1 > 1000;

猜你喜欢

转载自blog.csdn.net/u011500419/article/details/88639781
今日推荐