datastudio 里关于with as 的用法。

datastudio 里sql 语句的写法,加入with as 语法。

这样方便查询,易于维护。以后都这样写。

优点:

1 易于维护,可以复用代码块

2 优化书写逻辑,方便查阅理解。

3  性能方面优化(不确定)

WITH  a AS (
        select
        id,
        workstation_name,
        workstation_store_name
        from
            (select
            customer_passport_id id,
            workstation_name,
            workstation_store_name,
            row_number() over(partition by customer_passport_id order by contract_date) rank
            from f_bm_order_main
            )b where b.rank=1 ) 
            
select
concat(",",a.id),
a.workstation_name,
a.workstation_store_name
FROM a
LIMIT 10 ;

1. CTE后面必须直接跟使用CTE的SQL语句(如selectinsertupdate等),否则,CTE将失效。如下面的SQL语句将无法正

常使用CTE:
with 
cr as 
    select CountryRegionCode from person.CountryRegion where Name like 'C%' 
select from person.CountryRegion  -- 应将这条SQL语句去掉
-- 使用CTE的SQL语句应紧跟在相关的CTE后面-- 
select from person.StateProvince where CountryRegionCode in (select from cr) 
 
 
2. CTE后面也可以跟其他的CTE,但只能使用一个with,多个CTE中间用逗号(,)分隔,如下面的SQL语句所示:
with 
cte1 as 
    select from table1 where name like 'abc%' 
), 
cte2 as 
    select from table2 where id > 20 
), 
cte3 as 
    select from table3 where price < 100 
select a.* from cte1 a, cte2 b, cte3 c where a.id = b.id and a.id = c.id 
 
原文地址:https://www.cnblogs.com/sakura3/p/11897782.html