【问题标题】:How to do arithmetic operation on last n rows from different tables in postgresql without join如何在没有连接的情况下对postgresql中不同表的最后n行进行算术运算
【发布时间】:2022-01-21 00:24:56
【问题描述】:

我有两个表(例如表 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)。

P.S:我不能使用连接,因为此表中的行 ID 不相关

【问题讨论】:

  • 您的问题中的样本数据和所需结果将是有益的。

标签: sql postgresql


【解决方案1】:

您可以在id 上而不是row_number() 上使用join

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)

Fiddle

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多