使用t-sql以升序获取最后3行?

时间:2014-09-16 03:37:10

标签: sql sql-server tsql

CommentID   Name       Replies                             OrderID
313         Ed         dlfkndl sdknldgf dlffdg               496
313         James      sdsflsdf snflsf sfnslf sfnklsdf       499
313         Jeff       sdsflsdf snflsf sfnslf sfnklsdf       500
313         Alan       sdsflsdf snflsf sfnslf sfnklsdf       501
313         William    sdflksnfdlsk sdfknslnf slfnks         503

我上面有一个示例表,它按[OrderID]按升序排列。我想拿最后一个 该表的3行也按升序排列,如下所示。

CommentID   Name       Replies                              OrderID
313         Jeff       sdsflsdf snflsf sfnslf sfnklsdf        500
313         Alan       sdsflsdf snflsf sfnslf sfnklsdf        501
313         William    sdflksnfdlsk sdfknslnf slfnks          503

在T-SQL中执行此操作的确切语法是什么?谢谢... 我试图想出这个,但仍然没有以asc顺序取出最后3行。

SqlCommand cmd = new SqlCommand("SELECT * FROM [RepTab] WHERE [OrderID] > (SELECT MAX([OrderID]) - 3 FROM [RepTab] WHERE [CommentID]='" + Id + "') ", con);

3 个答案:

答案 0 :(得分:1)

选择子查询中的底部3条记录按顺序递减,然后按顺序排列外部升序。

Select *
from
  (select top 3 orderid, commentid, replies, name
   From
     [RepTab] 
   Order by orderid desc
   ) t
Order by order id

fiddle

答案 1 :(得分:1)

您也可以使用Common Table Expression编写查询:

With CTE as
( select row_number() over ( partition by CommentID order by OrderID desc) as rownum,
         CommentID,
         Name,
         Replies,
         OrderID
  From reptab
 ) 
 select  CommentID,
         Name,
         Replies,
         OrderID
 from CTE 
 where rownum <=3
 and CommentID = 313
 order by OrderID asc

答案 2 :(得分:0)

请尝试以下查询:

在上面的查询中,paqogomez错过了表别名

Select *
from
  (select top 3 orderid, commentid, replies, name
   From
     [RepTab] 
   Order by orderid desc
   ) as tbl
Order by orderid