【问题标题】:PostgreSQL:在子查询中查找值等于最大值的行
【发布时间】:2022-01-07 07:30:44
【问题描述】:

我有一个工作的 PostgreSQL,它使用多个连接,一个列是计算的结果。从该查询的结果中,我需要提取一列最大的行,并且可能有很多。如果没有,我可以ORDER BY that_column DESC LIMIT 1;我发现如果我只需要在现有数据库表上这样做,我可以这样做:

SELECT columns FROM table_name
WHERE that_coulmn = (SELECT MAX(that_column) FROM table_name)

但是,情况也并非如此。我有一个这样的查询:

SELECT z.xyz, (x.aa- x.bb) * y.qq as that_column 
FROM table_1 x
JOIN table_2 y ON x.foo = y.foo
JOIN table_3 z ON y.bar = z.bar
JOIN table_4 w ON w.baz = z.baz
where x.aa IS NOT NULL

现在,这行得通。现在我需要知道如何将其作为子查询并从中获取z.xyzthat_column 最大的行。有什么帮助吗?

【问题讨论】:

  • 我不明白。您查询中的所有内容都是正确的。你试过了吗?它是否应该与您已有的知识一起使用。
  • 查看横向连接

标签: sql postgresql subquery aggregate aggregate-functions


【解决方案1】:

我找到了!

我把它作为一个子查询,使用[rank](https://www.postgresqltutorial.com/postgresql-rank-function/) 以thatColumn 进行排名,然后将其放入另一个子查询中以获取具有 rank=1 的那些

SELECT xyz 
FROM 
    (xyz, thatColumn, RANK() OVER(ORDER BY thatColumn DESC) FROM (
         -- the subquery in the question
    )
) AS highest_and_rank
WHERE thatColumnRank = 1

感谢所有试图提供帮助的人。你太棒了。

【讨论】:

  • eshirvana 答案有什么区别?我认为这会礼貌地给予该人一些信任或将其标记为正确。
【解决方案2】:

如果您需要选择其他列作为输出:

select * from (
  select *, dense() over(order by (x.aa- x.bb) * y.qq desc) as that_column 
  from table_1 x
  join table_2 y ON x.foo = y.foo
  join table_3 z ON y.bar = z.bar
  join table_4 w ON w.baz = z.baz
  where x.aa IS NOT NULL
) t where that_column = 1

【讨论】:

    【解决方案3】:

    也许是这个?

    SELECT MAX(thatmax.that_column) as theMax FROM (
       SELECT z.xyz, (x.aa- x.bb) * y.qq as that_column 
       FROM table_1 x
       JOIN table_2 y ON x.foo = y.foo
       JOIN table_3 z ON y.bar = z.bar
       JOIN table_4 w ON w.baz = z.baz
       where x.aa IS NOT NULL
    ) thatmax
    

    【讨论】:

    • 这是一个很好的方向,但遗憾的是,这只会让我得到 thatColumn 本身的最大值,而不是更多关于该最大值来自哪里的列。
    • @CtrlAltDolev 但是您还需要哪些列?每个表的每一列?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-03
    • 2021-11-05
    • 1970-01-01
    • 1970-01-01
    • 2018-09-07
    • 1970-01-01
    • 2022-10-26
    相关资源
    最近更新 更多