开发者

SQL SELECT statement containing AS

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 ment开发者_C百科ion 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 c in a subquery:

select title, scale / next_scale, c
from ( select title, scale, 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 (select title, scale, scale * D0 AS c from signatures) signatures_calc
     ) agg
where agg_row = 1;


You can ORDER BY the ordinal number of the column:

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
order by 3;


When put the order by is the sub query, should fill the bill

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
       order by 3
 ) agg
where agg_row = 1;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜