从父样本中选择n个样本

时间:2015-09-08 11:28:24

标签: sql-server

我有一个包含样本层次结构的表。字段sample_number是关键字,并且标识父样本 由字段parent_aliquot。对于给定的父样本,存在0到20个等分样本的任何地方。每个等分试样也通过字段aliquot_number在其父样本中索引。 我可以为父样品选择所有等分试样:

select s2.sample_number, s1.sample_number, s1.aliquot_number
from sample s1
inner join sample s2 on s2.sample_number = s1.parent_aliquot
order by s2.sample_number, s1.aliquot_number desc

但是我想为每个父样本选择所有等分样本但是2(或n),留下两个样本具有最低的aliquot_number(可能不是1和2)。 怎么办呢?

1 个答案:

答案 0 :(得分:0)

您可以在以下内容中使用ROW_NUMBER

select sample_number, sample_number, aliquot_number
from (
   select s2.sample_number, s1.sample_number, s1.aliquot_number,
          row_number() over(partition by parent_aliquot order by aliquot_number) rn
   from sample s1
   inner join sample s2 on s2.sample_number = s1.parent_aliquot
     )x
where rn <= 2 -- here you specify how many rows you want to retrieve
order by sample_number, aliquot_number desc