Postgresql 按一列选择行值应仅重复N次

Postgresql 按一列选择行值应仅重复N次,postgresql,Postgresql,我的桌子是: id sub_id datetime resource ---|-----|------------|------- 1 | 10 | 04/03/2009 | 399 2 | 11 | 04/03/2009 | 244 3 | 10 | 04/03/2009 | 555 4 | 10 | 03/03/2009 | 300 5 | 11 | 03/03/2009 | 200 6 | 11 | 03/03/2009 | 500 7 | 11 |

我的桌子是:

id  sub_id datetime    resource
---|-----|------------|-------
1  | 10  | 04/03/2009 | 399 
2  | 11  | 04/03/2009 | 244
3  | 10  | 04/03/2009 | 555
4  | 10  | 03/03/2009 | 300
5  | 11  | 03/03/2009 | 200
6  | 11  | 03/03/2009 | 500
7  | 11  | 24/12/2008 | 600
8  | 13  | 01/01/2009 | 750
9  | 10  | 01/01/2009 | 760
10 | 13  | 01/01/2009 | 570
11 | 11  | 01/01/2009 | 870
12 | 13  | 01/01/2009 | 670
13 | 13  | 01/01/2009 | 703
14 | 13  | 01/01/2009 | 705
我只需要为每个sub_id选择2次

结果将是:

id  sub_id datetime    resource
---|-----|------------|-------
1  | 10  | 04/03/2009 | 399 
3  | 10  | 04/03/2009 | 555
5  | 11  | 03/03/2009 | 200
6  | 11  | 03/03/2009 | 500
8  | 13  | 01/01/2009 | 750
10 | 13  | 01/01/2009 | 570
如何在postgres中实现此结果?

使用窗口功能


查看我使用id匹配您的样本的订单列:

t=# with data as (select *,count(1) over (partition by sub_id order by id) from t)
select id,sub_id,datetime,resource from data where count <3;
 id | sub_id |  datetime  | resource
----+--------+------------+----------
  1 |     10 | 2009-03-04 |      399
  3 |     10 | 2009-03-04 |      555
  2 |     11 | 2009-03-04 |      244
  5 |     11 | 2009-03-03 |      200
  8 |     13 | 2009-01-01 |      750
 10 |     13 | 2009-01-01 |      570
(6 rows)

我想你需要定义顺序-我该如何从众多的子id中选择哪两个?对于每个子id,前两行都将被选择。我一点也不知道。我也不知道+1.
t=# with data as (select *,count(1) over (partition by sub_id order by id) from t)
select id,sub_id,datetime,resource from data where count <3;
 id | sub_id |  datetime  | resource
----+--------+------------+----------
  1 |     10 | 2009-03-04 |      399
  3 |     10 | 2009-03-04 |      555
  2 |     11 | 2009-03-04 |      244
  5 |     11 | 2009-03-03 |      200
  8 |     13 | 2009-01-01 |      750
 10 |     13 | 2009-01-01 |      570
(6 rows)