简体   繁体   English

将 CTE Query 转换为普通 Query

[英]Convert CTE Query into normal Query

I want to convert my @PostgreSQL, CTE Query, into Normal Query because the cte function is mainly used in data warehouse SQL and not efficient for Postgres production DBS.我想将我的@PostgreSQL CTE 查询转换为普通查询,因为 cte function 主要用于数据仓库 SQL 并且对于 Postgres 生产 DBS 效率不高。 So, need help in converting this CTE query into a normal Query因此,需要帮助将此 CTE 查询转换为普通查询

WITH
cohort AS (
    SELECT
        *
    FROM (
        select 
        activity_id,
        ts,
        customer,
        activity,
        case 
        when activity = 'completed_order' and lag(activity) over (partition by customer order by ts) != 'email' 
        then null
        when activity = 'email' and lag(activity) over (partition by customer order by ts) !='email' 
        then 1
        else 0
    end as cndn
        
        from activity_stream where customer in (select customer from activity_stream where activity='email') 
        order by ts
) AS s 

)
(
    select 
        *               
      from cohort as s
where cndn = 1 OR cndn is null order by ts)


You may just inline the CTE into your outer query:您可以将 CTE 内联到外部查询中:

select *               
from
(
    select activity_id, ts, customer, activity,
           case when activity = 'completed_order' and lag(activity) over (partition by customer order by ts) != 'email' 
                then null
                when activity = 'email' and lag(activity) over (partition by customer order by ts) !='email' 
                then 1
                else 0
           end as cndn
    from activity_stream
    where customer in (select customer from activity_stream where activity = 'email') 
) as s
where cndn = 1 OR cndn is null
order by ts;

Note that you have an unnecessary subquery in the CTE, which does an ORDER BY which won't "stick" anyway.请注意,您在 CTE 中有一个不必要的子查询,它执行ORDER BY无论如何都不会“坚持”。 But other than this, you might want to keep your current code as is.但除此之外,您可能希望保持当前代码不变。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM