公用表表达式(CTE)是从WITH子句中指定的简单查询派生的临时结果集(会把查询的表数据放到内存中,供其他查询随时使用),该子句紧跟在SELECT或INSERT关键字之前。CTE仅在单个语句的执行范围内定义。可以在Hive SELECT,INSERT, CREATE TABLE AS SELECT或CREATE VIEW AS SELECT语句中使用一个或多个CTE 。
在 select 中使用 CTE
with q1 as ( select key from src where key = '5')
select *
from q1;
-- from style
with q1 as (select * from src where key= '5')
from q1
select *;
-- chaining CTEs
with q1 as ( select key from q2 where key = '5'),
q2 as ( select key from src where key = '5')
select * from (select key from q1) a;
-- union example
with q1 as (select * from src where key= '5'),
q2 as (select * from src s2 where key = '4')
select * from q1 union all select * from q2;
CTE in Views, CTAS, and Insert Statements
-- insert example
create table s1 like src;
with q1 as ( select key, value from src where key = '5&