Reputation: 590
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
I have a sample table above which is in an ascending order by [OrderID]. I want to fetch the last 3 rows of the table which is in an ascending order as well which is shown below.
CommentID Name Replies OrderID
313 Jeff sdsflsdf snflsf sfnslf sfnklsdf 500
313 Alan sdsflsdf snflsf sfnslf sfnklsdf 501
313 William sdflksnfdlsk sdfknslnf slfnks 503
What is the exact syntax to do this in T-SQL? Thanks... I tried to come up with this but still not not fetching the last 3 rows in an asc order.
SqlCommand cmd = new SqlCommand("SELECT * FROM [RepTab] WHERE [OrderID] > (SELECT MAX([OrderID]) - 3 FROM [RepTab] WHERE [CommentID]='" + Id + "') ", con);
Upvotes: 2
Views: 1307
Reputation: 10274
You can also write the query using Common Table Expression
as:
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
Upvotes: 1
Reputation: 15865
Selecting the bottom 3 records in a subquery ordered descending, then order the outer ascending.
Select *
from
(select top 3 orderid, commentid, replies, name
From
[RepTab]
Order by orderid desc
) t
Order by order id
Upvotes: 1
Reputation: 447
Please try below query :
In above query paqogomez missed the table alias
Select *
from
(select top 3 orderid, commentid, replies, name
From
[RepTab]
Order by orderid desc
) as tbl
Order by orderid
Upvotes: 0