with嵌套子查询用法
在比较复杂,数据量大的情况下,为了提高查询效率,需要用到一些子查询。一层一层嵌套的子查询不方便,显得sql语句比较繁琐。可以用 with语句 构建临时表查询:具体用法如下:
--只有一个临时表时
with tmp as (
select empno ,ename ,sal
from db_hive.emp)
select t.empno,t.ename,t.sal from tmp t ;
--注释:查询db_hive 数据库中 emp 中empno ,ename ,sal 字段
--有多个临时表时 多个临时表 用 , 号 隔开 最后一个不需要 , 号
with
sale_store_categroy_all_fact_01 as (
business_date
,'01' as date_type --新增一个列 列名为date_type 该列值设置为 ‘01’
,'日汇总' as date_type_name
,'0' as is_summary
,store_id
,store_name
,'01' as categroy_type
,'大分类' as categroy_type_name
,business_date as inc_day
from dal.dal_article_daily_sales
where business_date ='2019-10-08'
group by
business_date
,store_id
,store_name),
sale_store_categroy_all_fact_02 as (
select
business_date
,'01' as date_type
,'日汇总' as date_type_name
,'0' as is_summary
,store_id
,store_name
,'02' as categroy_type
,'中分类' as categroy_type_name
,business_date as inc_day
from dal.dal_article_daily_sales
where business_date ='2019-10-08'
group by
business_date
,store_id
,store_name )
--往临时表插入数据
insert overwrite table tmp_dal_api.sale_store_categroy_all_fact partition (inc_day)
select
business_date --营业日期
,date_type
,date_type_name --日期类型名称
,is_summary --是否汇总数据
,store_id --门店编码
,store_name --门店名称
,categroy_type --分类类型 01:大类 02:中类 03:小类
,categroy_type_name --分类类型名称
from (
select sale_store_categroy_all_fact_01.* from sale_store_categroy_all_fact_01
union all
select sale_store_categroy_all_fact_02.* from sale_store_categroy_all_fact_02 )a;
更多推荐
sql语句中with用法
发布评论