I have the SQL query:
select title, scale / next_scale, c
from ( select title, scale, scale*D0 AS c,
lead(scale) over(partition by title order by scale asc) as next_scale,
row_number() over(partition by title order by scale asc) as agg_row
from signatures
) agg
where agg_row = 1;
and it works as expected. However, what I really want the sorting “scale” value to be an arithmetic operation between several columns, so I tried using an AS clause (shown above) and modify the query to:
select title, scale / next_scale, c
from ( select title, scale, scale*D0 AS c,
lead(scale) over(partition by title order by c asc) as next_scale,
row_number() over(partition by title order by c asc) as agg_row
from signatures
) agg
where agg_row = 1;
However, it fails at the ORDER BY c. Why is this? I can substitute ORDER BY scale*D0 and it works just fine. However, I will eventually want to use a term like: scale*D0*D1*D2*...*D100; and I don’t want to have to calculate that 3 different times – not to mention the physical length of the query. I am hoping to have scale*D0*D1*D2*...*D100 AS c and then ORDER BY c.
Is this possible?
I am using PostgreSQL.
Many thanks,
Brett
Calculate
cin a subquery: