获取每个序列号的第n条记录

时间:2018-08-24 11:49:52

标签: sql ms-access

我有一个看起来像这样的表:

ID | SerialNumber | SomeData
---|--------------|---------
1  | 1            | abc
2  | 1            | def
3  | 1            | ghi
4  | 1            | jkl
5  | 2            | mno
6  | 2            | pqr

现在,我希望查询为每个序列号的每个第n个ID返回“ SomeData”(如果该序列号存在该第n个ID)。因此,如果n=2,我想要的输出是:

ID | SerialNumber | SomeData
---|--------------|---------
2  | 1            | def
6  | 2            | pqr

我认为这已经是解决方案的一半,但是我不知道如何使它达到我想要的目的:How to find 11th entry in SQL Access database table?

1 个答案:

答案 0 :(得分:0)

MS Access是这类数据库的糟糕数据库。您可以使用子查询枚举值,然后将其用于选择:

select t.*
from (select t.*,
             (select count(*)
              from <your table> as t2
              where t2.serialnumber = t.serialnumber and t2.id <= t.id
             ) as seqnum
      from <your table> as t
     ) as t
where seqnum = 2;

实际上不需要中间子查询。您可以将相关子查询放在where子句中。我发现此表格的意图更加清晰。