Skip to content
Advertisement

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. So, need help in converting this CTE query into a normal Query

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)


Advertisement

Answer

You may just inline the CTE into your outer query:

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. But other than this, you might want to keep your current code as is.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement