假设您在PostgreSQL上有以下users
表:
id | group_id | name | age
---|----------|---------|----
1 | 1 | adam | 10
2 | 1 | ben | 11
3 | 1 | charlie | 12 <-
3 | 2 | donnie | 20
4 | 2 | ewan | 21 <-
5 | 3 | fred | 30 <-
如何仅按group_id
(用箭头标记的)从最早的用户查询所有列?
我尝试过使用group by
,但是一直按"users.id" must appear in the GROUP BY clause
。
(注意:我必须将查询工作到Rails AR模型范围中。)
答案 0 :(得分:1)
您可以使用ROW_NUMBER/RANK
(如果可能的话)窗口函数:
SELECT *
FROM (SELECT *,ROW_NUMBER() OVER(PARTITION BY group_id ORDER BY age DESC) AS rn
FROM tab) s
WHERE s.rn = 1;
答案 1 :(得分:1)
您可以在联接中使用子查询并增加结果
select m.*
from users m
inner join (
select group_id, max(age) max_age
from users
group by group_id
) AS t on (t.group_id = m.group_id and t.max_age = m.age)
答案 2 :(得分:1)
经过一些挖掘,您可以使用PostgreSQL的select distinct on (users.group_id) users.*
from users
order by users.group_id, users.age desc;
-- you might want to add extra column in ordering in case 2 users have the same age for same group_id
:
User
.select('DISTINCT ON (users.group_id), users.*')
.order('users.group_id, users.age DESC')
在Rails中翻译为:
DISTINCT ON
有关.InitialFileName = CurrentProject.Path 'Or any path
的一些文档:https://www.postgresql.org/docs/9.3/sql-select.html#SQL-DISTINCT