我正在尝试使用带postgres的CTE子查询,但查询错误。主要问题是:我可以在子查询内使用cte-在窗口表达式内使用revenue
吗?也许还有另一种解决方案可以得到相同的结果。
这摘自postgres练习:https://pgexercises.com/questions/aggregates/classify.html
但是我想在这里使用cte。
WITH agg AS
(SELECT name,
sum(CASE
WHEN memid = 0 THEN slots * guestcost
ELSE slots * membercost
END) AS revenue
FROM cd.bookings b
JOIN cd.facilities f ON b.facid = f.facid
GROUP BY name)
SELECT name,
(CASE
WHEN rank = 1 THEN 'high'
WHEN rank = 2 THEN 'average'
ELSE 'low'
END) AS revenue1
FROM (
SELECT name, ntile(3) OVER(ORDER BY revenue DESC) AS rank
FROM agg;
) AS agg2;
更新:
CTE编写正确,但是据我了解,我不能在CTE之后写这样的东西:
select name from (
select name
from agg;
) as agg2;