我有一个表"the_table",其中包含三个字段:"id"(主键(,"a"和"b"。我需要为每个"a"选择"b"具有该"a"最大值的行。然后我运行查询:
select x.a, x.id
from the_table x
where b = ( select max( b ) where a = x.a )
这个查询挂起了我的PostgreSQL服务器。
我尝试了另一个查询:
select x.a, max( x.id )
from the_table x
where b = ( select max( b ) where a = x.a )
group by x.a
但结果是一样的。
这些查询有什么问题?
感谢您的任何回复!
如果您只想查看"a"中每个值的一条记录,则 Postgres对此有很棒的DISTINCT ON条款。
select distinct on (a) id, a, b
from the_table t
order by a, b desc, id
顺序很重要 - 首先在"distinct on"子句中列出列 - 在您的情况下只是"a"列,然后按照您希望的方式对数据进行排序 - 在您的情况下,您希望看到最大 b 所以"b desc">
如果要返回"a"的"b = max(b("的所有记录,则
select id, a, b
from (select id, a, b, rank() over(partition by a order by b desc) rnk
from the_table) a
where rnk=1
一个很好的提示 - 永远不要在 WHERE 语句中使用嵌套的选择。 如果数据库的记录更多,那么如果不是更糟,您将等待很长时间才能看到结果。
子查询中需要一个 from 子句。
select x.a, x.id
from the_table x
where b = (select max( b ) from the_table x where a = x.a )
我怀疑alias
的问题,当然还有from
子句:
select x.*
from the_table x
where x.b = ( select max(x1.b) from the_table x1 where x1.a = x.a );
当然,如果您只想要最大id
而不是其他信息,请使用group by
子句: