我有一个由多个子查询组成的查询。我使用'join'作为我不允许使用'with'。子查询具有“from”子句,这会产生问题。
我必须显示两列,每列包含要显示的特定逻辑。为了打印这两列,我需要使用需要'from'子句的子查询。我不确定如何编写'from'子句以适应整个查询并使其可运行。我检查了各个查询,它们都运行正常。
select lead(dt) over
(partition by t1.id_user order by f.topup_date desc rows between 0
preceding and unbounded following )
from
(select *,
(max(case when f.topup_value >= 20 then f.topup_date end) over (partition
by f.id_user order by f.topup_date desc rows between 0 preceding and
unbounded following )) as dt
from topups f) as f, //(<-I think this is incorrect)
CAST(f.topup_value as float)/CAST(t1.topup_value as float) from
(SELECT t1.seq,t1.id_user,t1.topup_value,row_number()
over (partition by t1.id_user order by t1.topup_date )
as rowrank from topups t1) as t1
inner join topups f on f.id_user=t1.id_user
inner join topups t2 on t1.seq=t2.seq
您收到语法错误,因为查询只能有一个FROM子句。很难说出你想要实现的结果,但是将第一个查询转换为非相关子查询并将其用于列f可能就是你要找的:
select
(select lead(dt) over (partition by t1.id_user order by f.topup_date desc rows between 0 preceding and unbounded following )
from (
select *,
(max(case when f.topup_value >= 20 then f.topup_date end) over (partition by f.id_user order by f.topup_date desc rows between 0 preceding and unbounded following )) as dt
from topups f
) x) as f,
CAST(f.topup_value as float)/CAST(t1.topup_value as float)
from (
SELECT t1.seq, t1.id_user, t1.topup_value, row_number() over (partition by t1.id_user order by t1.topup_date ) as rowrank
from topups t1
) as t1
inner join topups f on f.id_user=t1.id_user
inner join topups t2 on t1.seq=t2.seq
真的很难读懂那个查询。你标记为可能的错误是错误的,因为你试图在原来的SELECT
条款之后添加看起来像另一个FROM
的东西。这是不正确的语法。将您的FROM
子查询视为临时表。你不能说:
SELECT some_column
FROM a_table, some_other_column
这是交叉连接语法。 some_other_column
需要成为一个表甚至有效。
考虑添加CREATE TABLE
和样本数据,以便我们进行测试。
您可能正在寻找以下内容:
SELECT LEAD(temp.dt) OVER(PARTITION BY temp.id_user ORDER BY temp.topup_date DESC ROWS BETWEEN 0 PRECEDING AND UNBOUNDED FOLLOWING)
, temp.division
FROM
(
SELECT (max(CASE WHEN f.topup_value >= 20 THEN f.topup_date END) OVER(PARTITION BY f.id_user ORDER BY f.topup_date DESC ROWS BETWEEN 0 PRECEDING AND UNBOUNDED FOLLOWING )) AS dt
, f.topup_value::float / t1.topup_value::float AS division
, t1.id_user
, f.topup_date
FROM topups t1
JOIN topups f USING (id_user)
) temp
;
只是一个意见,但使用::
运算符来输出变量的噪音较小。而不是CAST(f.topup_value as float)
只使用f.topup_value::float