如何使用Postgresql查找组中最早的记录?

如何使用Postgresql查找组中最早的记录?,sql,postgresql,Sql,Postgresql,考虑“book”表中的以下数据集(组id、标题、签出日期): 我需要编写一个查询,返回每个组(组1和组2)中最早的“check_out_date”值的记录。这应该很容易——我只是不知道怎么做。我想你需要这样的东西 select group_id, title, check_out_date from book b1 where check_out_date = (select MIN(check_out_date) from boo

考虑“book”表中的以下数据集(组id、标题、签出日期):


我需要编写一个查询,返回每个组(组1和组2)中最早的“check_out_date”值的记录。这应该很容易——我只是不知道怎么做。

我想你需要这样的东西

 select group_id, title, check_out_date from book b1 
       where
       check_out_date = 
       (select MIN(check_out_date) 
       from book b2 where b2.group_id =  b1.group_id)

现在postgres支持窗口功能

SELECT group_id, title, checkout_date) FROM
 (SELECT group_id, 
  title, 
  checkout_date, 
  rank() OVER (PARTITION BY group_id ORDER BY checkout_date) AS rk
 ) AS subq
WHERE rk=1;

您可能需要
(组id、签出日期)
上的索引,反之亦然。我还没有打开足够的窗口来了解计划者试图做什么。

我想你指的是最小值,而不是最大值;MAX将返回最新的日期,而不是最早的日期。除此之外,SQL完成了所需的工作!是的,谢谢@NickShaw。我以为我们在找最新的。哦。固定的
SELECT group_id, title, checkout_date) FROM
 (SELECT group_id, 
  title, 
  checkout_date, 
  rank() OVER (PARTITION BY group_id ORDER BY checkout_date) AS rk
 ) AS subq
WHERE rk=1;