如何仅选择SQL Server中的第三行或第四行

如何仅选择SQL Server中的第三行或第四行,sql,sql-server,Sql,Sql Server,我在想办法只选择我正在编写的查询中的第三行或第四行时遇到了一点困难,如果有任何帮助,我将不胜感激 这是我提出的代码的一个示例,但是它只选择第一行 Left Outer Join (select ap_attachments.ap_table_key, ap_description, ap_creation_date, ap_creation_time, ap_file_name, ap_attach_id from ap_attachments

我在想办法只选择我正在编写的查询中的第三行或第四行时遇到了一点困难,如果有任何帮助,我将不胜感激

这是我提出的代码的一个示例,但是它只选择第一行

Left Outer Join (select ap_attachments.ap_table_key, ap_description, ap_creation_date, ap_creation_time, ap_file_name, ap_attach_id
                     from ap_attachments
                          inner join (select Min(ap_attachment_id) ap_attach_id, ap_table_key
                                      from ap_attachments
                                      where ap_file_name like '%jpg%'
                                      group by ap_table_key) C 
                             On ap_attachments.ap_attachment_id = C.ap_attach_id) apImgThree_attach 
        On apImgTwo_attach.ap_table_key = order_link.to_order_id

您可以使用
行编号()
函数执行此操作:

select ap_attachment_id, ap_table_key,ROW_NUMBER() OVER(PARTITION BY ap_table_key ORDER BY ap_attachment_id) AS RN
from ap_attachments
where ap_file_name like '%jpg%'
然后可以使用
RN
值指定要返回的行。这可能需要一些调整,具体取决于源数据,
densite\u RANK()
函数可能更合适


ROW\u NUMBER()
函数为每行分配一个数字。
分区是可选的,但用于重新开始该组中每个值的编号,即:如果您按某个日期进行分区,则对于每个唯一的日期值,编号将从1开始
ORDER BY
当然用于定义计数方式,并且在
ROW_NUMBER()
函数中是必需的。

查找提前期和滞后期的单据。您还可以使用PARTITION子句在特定日期内创建窗口,例如

declare @table table(
[flower] [sysname]);
insert into @table
        ([flower])
values      (N'rose'),
        (N'tulip'),
        (N'chamomile'),
        (N'lily');
select [flower] from   @table order  by [flower];
select [flower]
   , lag ([flower]
          , 1
          , 0)
       over (
         order by [flower] desc) as [previous_flower]
   , lead ([flower]
           , 1
           , 0)
       over (
         order by [flower] desc) as [next_flower]
from   @table; 
签出
行号()