简单查询挂起PostgreSQL
我有一个表\u表,它有三个字段:id主键、a和b。我需要为每个a选择b对该a具有最大值的行。然后我运行查询:简单查询挂起PostgreSQL,sql,postgresql,Sql,Postgresql,我有一个表\u表,它有三个字段: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 server 我尝试了另一个查询: select x.a, max( x.id ) from the_table x where b = ( select max( b ) where a = x
select x.a, x.id
from the_table x
where b = ( select max( b ) where a = x.a )
此查询挂起我的PostgreSQL server
我尝试了另一个查询:
select x.a, max( x.id )
from the_table x
where b = ( select max( b ) where a = x.a )
group by x.a
但结果是一样的
这些疑问有什么不对
谢谢你的回复 在子查询中需要from子句
select x.a, x.id
from the_table x
where b = (select max( b ) from the_table x where a = x.a )
我怀疑别名有问题&当然是从第条:
select x.*
from the_table x
where x.b = ( select max(x1.b) from the_table x1 where x1.a = x.a );
当然,如果您只需要最大id而不是其他信息,那么可以使用GROUPBY子句:如果您只想在then中看到每个值的一条记录 Postgres对此有非常独特的ON子句
select distinct on (a) id, a, b
from the_table t
order by a, b desc, id
顺序很重要-首先是distinct on子句中的列列表-在您的情况下仅为一列,然后按您希望的方式对数据进行排序-在您的情况下,您希望看到max b so b desc
如果要返回a的所有记录,其中b=maxb,则
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语句中使用嵌套选择。
如果DB有更多的记录,那么即使不是更糟的记录,您也要等很长时间才能看到结果 子查询中没有FROM子句?@jarlh它会使用该语法运行吗?它不会挂起,它会等待查询的其余部分,因为您尚未使用分号终止它;在你陈述的最后。如果您使用的是psql,请注意提示已更改,表示语句尚未完成,正在等待您结束。非常感谢!我将使用第一种解决方案对不起。我简化了查询,但没有测试它。真正的查询是:选择ch.loan,max ch.id from cache\u loan\u Sum\u Per\u Hour ch其中stat\u datetime=选择max stat\u datetime from cache\u loan\u Sum\u Per\u Hour其中loan=ch.loan按ch.loan分组,另一个查询是:选择ch.loan,每小时缓存贷款总额中的ch.id,其中stat\U datetime=从每小时缓存贷款总额中选择最大stat\U datetime,其中Loan=ch.Loan