[英]Convert CTE Query into normal Query
我想將我的@PostgreSQL CTE 查詢轉換為普通查詢,因為 cte function 主要用於數據倉庫 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
無論如何都不會“堅持”。 但除此之外,您可能希望保持當前代碼不變。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.