【问题标题】:Find max in group by in postgresql在 postgresql 中查找分组中的最大值
【发布时间】:2021-11-05 22:55:33
【问题描述】:

这是我的学生桌。我想显示在宿舍中拥有 max(parent_inc) 的学生的宿舍、rollno、parent_inc。当我尝试这个命令时 -

select hostel, rollno, max(parent_inc) from students group by hostel;

出现错误 -

column "students.rollno" must appear in the GROUP BY clause or be used in an aggregate function
select hostel, rollno, max(parent_inc) from students group b...

如何正确获取?

如果不选择 rollno 字段,它可以正常工作。

【问题讨论】:

  • 您需要将测试数据发布为格式化文本 - 不是图像。请参阅Why no images 或更好地创建fiddle

标签: postgresql greatest-n-per-group


【解决方案1】:

试试MAX函数的窗口版本:

select rollno
      , hostel
      , max(parent_inc) over(partition by hostel) max_parent_inc 
   from students; 

注意:未经测试

【讨论】:

  • OP 希望分组:“rollno,parent_inc of the student who has max(parent_inc) in a hostel
  • @belayer 不,它没有按预期工作。它只是给出了学生表中所有记录的rollno,hostel,parent_inc,按hostel格式排序。但我需要每个旅馆的 max_parent_inc。虽然我尝试在 rollno 列上使用 array_agg 函数,但它返回了正确的输出。
  • 很高兴你得到它。看来我误解了你想要的东西。这就是为什么您需要发布清晰标记的示例数据(作为文本 - 无图像)和预期输出。请参阅Why no images 和这里制作text tables。或者只是创建一个fiddle
猜你喜欢
  • 2022-01-07
  • 2012-04-12
  • 1970-01-01
  • 2012-08-14
  • 1970-01-01
  • 1970-01-01
  • 2018-05-03
  • 2020-08-20
相关资源
最近更新 更多