使用TOP和ORDER BY在SQL Server中选择第n行

时间:2015-11-19 15:21:13

标签: sql sql-server

我正在尝试从表中选择第n行。我知道如何做到这一点,但它无法正常工作。

我尝试过:目前我选择前6名按顺序排序。然后我按照desc顺序选择前1。这应该给我第6个实例。

持续发生的事情:无论我做什么,我总是得到第一个实例。我可以更改“前6名”并更改asc和desc或命令,我总是得到第一个实例。

这不是完整的代码,它涉及UNION并且难以使用row_number()。因为我需要交叉应用它会使CTE变得困难。有没有人看到我显然做错了什么?

update t2
set RWK3_OPERATION_CODE = (select top 1 t3.OPERATION_CODE)       

From plant.PIECE_DETAIL t2
full join app.OHCMS_TRACE_SN_XREF t4
on t2.TRACE_ID = t4.TRACE_ID
cross apply
(Select top 1 * from 
     (Select top 6 * from (
               Select
                      t1.TRACE_ID
                     ,t1.OPERATION_CODE
                     ,t1.OPERATION_START_DATE_D 
                     ,t1.OPERATION_START_TIME
              from app.OHCMS_ITEM_OPERATION_TRACE t1
              where t1.TRACE_ID = t2.TRACE_ID
              )as t5 
              order by (OPERATION_START_DATE_D), (OPERATION_START_TIME) 
    )as t6
    order by (OPERATION_START_DATE_D), (OPERATION_START_TIME) desc
)as t3

Where t2.rwk_cycle > 10

3 个答案:

答案 0 :(得分:3)

ORDER BY的每个部分都默认为ASC,除非您使用明确的DESC覆盖。

在你的行......

order by (OPERATION_START_DATE_D), (OPERATION_START_TIME) desc

...它的处理方式与您键入的内容相同......

order by (OPERATION_START_DATE_D) ASC, (OPERATION_START_TIME) desc

你想......

order by (OPERATION_START_DATE_D) DESC, (OPERATION_START_TIME) desc

以下是完整查询(只是原件的复制和粘贴以及更正的ORDER BY

update t2
set RWK3_OPERATION_CODE = (select top 1 t3.OPERATION_CODE)       

From plant.PIECE_DETAIL t2
full join app.OHCMS_TRACE_SN_XREF t4
on t2.TRACE_ID = t4.TRACE_ID
cross apply
(Select top 1 * from 
     (Select top 6 * from (
               Select
                      t1.TRACE_ID
                     ,t1.OPERATION_CODE
                     ,t1.OPERATION_START_DATE_D 
                     ,t1.OPERATION_START_TIME
              from app.OHCMS_ITEM_OPERATION_TRACE t1
              where t1.TRACE_ID = t2.TRACE_ID
              )as t5 
              order by (OPERATION_START_DATE_D), (OPERATION_START_TIME) 
    )as t6
    order by 
      (OPERATION_START_DATE_D) DESC, 
      (OPERATION_START_TIME) desc
)as t3
Where t2.rwk_cycle > 10

答案 1 :(得分:2)

你有没有看过row_number() function?它将提供一种在有序结果集中查找第6个值的替代路径。它基本上为每行提供一个数字,当与sort子句结合使用时,允许您在where子句中为行号指定特定值。一般形式将是这样的:

Select subTable.* 
From (Select a.a, row_number() Over(Order by a.b desc) as orderedRow
    From a) as subTable
Where subTable.orderedRow = 6

编辑:我还应该提到这只适用于SQL Server 2005及更高版本 - 而不是SQL Server 2000,并且它并不存在于所有数据库平台中。

答案 2 :(得分:0)

$reportQuery = 'SELECT CampaignId,CampaignName, '
        . 'Impressions, Clicks, Cost FROM CAMPAIGN_PERFORMANCE_REPORT DATE 20151119 ';
       // . 'WHERE Status IN [Campagne mise en veille, PAUSED] DURING ' . $dateRange;
  // Set additional options.
  $options = array('version' => ADWORDS_VERSION);
 ReportUtils::DownloadReportWithAwql($reportQuery, $filePath, $user,
      $reportFormat, $options);
  $dataArray =file($filePath);