将 CTE 查询转换为普通查询
Convert CTE Query into normal Query
我想将我的@PostgreSQL、CTE 查询转换为普通查询,因为 cte 函数主要用于数据仓库 SQL,对于 Postgres 生产 DBS 效率不高。
因此,需要帮助将此 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)
您可以将 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;
请注意,您在 CTE 中有一个不必要的子查询,它执行的 ORDER BY
无论如何都不会“坚持”。但除此之外,您可能希望保持当前代码不变。
我想将我的@PostgreSQL、CTE 查询转换为普通查询,因为 cte 函数主要用于数据仓库 SQL,对于 Postgres 生产 DBS 效率不高。 因此,需要帮助将此 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)
您可以将 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;
请注意,您在 CTE 中有一个不必要的子查询,它执行的 ORDER BY
无论如何都不会“坚持”。但除此之外,您可能希望保持当前代码不变。