包含 AS 的 SQL SELECT 语句
我有 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。
非常感谢, 布雷特
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在子查询中计算
c
:Calculate
c
in a subquery:您可以按列的序号进行排序:
You can ORDER BY the ordinal number of the column:
下订单时是子查询,应该填单
When put the order by is the sub query, should fill the bill