我有SQL查询:
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;
它按预期工作。但是,我真正希望排序“scale”值是几列之间的算术运算,所以我尝试使用AS子句(如上所示)并将查询修改为:
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;
然而,它在ORDER BY c
失败了。为什么是这样?我可以替换ORDER BY scale*D0
并且它可以正常工作。但是,我最终会想要使用像scale*D0*D1*D2*...*D100
这样的术语;而且我不想计算3次不同的时间 - 更不用说查询的物理长度了。我希望有scale*D0*D1*D2*...*D100 AS c
然后ORDER BY c
。
这可能吗?
我正在使用PostgreSQL。
非常感谢, 布雷特
答案 0 :(得分:3)
在子查询中计算c
:
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;
答案 1 :(得分:1)
您可以按列的序号进行排序:
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;
答案 2 :(得分:0)
当下订单时是子查询,应该填写账单
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;