繁体   English   中英

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

[英]How to select just the third or fourth row in 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
                          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

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

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值指定要返回的行。 这可能需要一些调整,具体取决于您的源数据, DENSE_RANK()函数可能更合适。

ROW_NUMBER()函数为每一行分配一个数字。 PARTITION BY是可选的,但用于为该组中的每个值重新开始编号,即:如果您对PARTITION BY Some_Date进行编号,则对于每个唯一的日期值,编号将从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; 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM