[英]How to do arithmetic operation on last n rows from different tables in postgresql without join
我有兩個表(例如表 a 列 c, d 和表 b 列 e)。 我正在嘗試像這樣進行數學運算: (c + d) * e 對於此表中最后n行中的每一行( ORDER BY id desc limit n
)保持行的順序。
我已經嘗試過這個查詢:
SELECT f1.r1 * f2.r2
FROM (
select c + d as r1
from a
order by id desc
limit n
) as f1,
(select e as r2
from b
order by id desc
limit n) as f2
但它返回 n^2 列(我只需要 n)。
PS:我不能使用連接,因為此表中的行 ID 不相關
您可以使用join
不是id
而是row_number()
:
with u as
(select c, d, row_number() over(order by id desc) as rownum_a from a),
v as (select e, row_number() over(order by id desc) as rownum_b from b)
(select c, d, e, (c + d)*e as "(c+d)*e" from u inner join v on rownum_a =
rownum_b limit n)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.