Sql 每个组具有多个结果的最大函数

Sql 每个组具有多个结果的最大函数,sql,postgresql,Sql,Postgresql,我正在寻找有关postgresql查询的帮助 示例输入数据如下所示: pk name ========================= 1 | notebook cz-2001 2 | notebook cz-2002 3 | notebook cz-2003 4 | notebook cz-2003 5 | notebook cz-2003 6 | notebook cz-2004 7 | notebook cz-2004 8 | notebook cz-2

我正在寻找有关postgresql查询的帮助

示例输入数据如下所示:

pk  name
=========================
1   | notebook cz-2001
2   | notebook cz-2002
3   | notebook cz-2003
4   | notebook cz-2003
5   | notebook cz-2003
6   | notebook cz-2004
7   | notebook cz-2004
8   | notebook cz-2004
9   | notebook cz-2004
10  | notebook cz-2005
11  | notebook cz-2006
12  | notebook cz-2007
13  | notebook cz-2008
14  | notebook cz-2009
在notebook cz-2003和notebook cz-2004的名称列中,某些行的值相同

通过此查询,我可以获得分组名称的最大pk值:

select * from test_group where pk in
(
select max(pk) from test_group group by name order by name
)
结果:

pk  name
=========================
1   | notebook cz-2001
2   | notebook cz-2002
5   | notebook cz-2003
9   | notebook cz-2004
10  | notebook cz-2005
11  | notebook cz-2006
12  | notebook cz-2007
13  | notebook cz-2008
14  | notebook cz-2009
但我不知道,这是我的问题,如何得到例如二三,四。。。分组名称的最高pk值

预期结果,例如两个最高峰值:

pk  name
=========================
1   | notebook cz-2001
2   | notebook cz-2002
4   | notebook cz-2003
5   | notebook cz-2003
8   | notebook cz-2004
9   | notebook cz-2004
10  | notebook cz-2005
11  | notebook cz-2006
12  | notebook cz-2007
13  | notebook cz-2008
14  | notebook cz-2009
你能给我一些提示如何做到这一点吗

谢谢

JP

您可以使用:

选择主键、名称 从…起 按名称顺序按主键描述在分区上选择*,行号 从我的桌子上 s
其中行数一种方法是窗口函数:

select tg.*
from (select tg.*,
             row_number() over (partition by name order by pk desc) as seqnum
      from test_group tg
     ) tg
where seqnum <= ?;
select tg.*
from test_group tg
where tg.pk >= any (select tg2.pk
                    from test_group tg2
                    where tg2.name = tg.name
                   );