简体   繁体   中英

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 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 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM