This article is half-done without your Comment! *** Please share your thoughts via Comment ***
Check the below input data and expected output to get the last three records of a table.
Input Data:
1 2 3 4 5 6 7 8 9 10 11 |
ID Name ----------- ---------- 1 ABC 2 XYZ 3 ERZ 4 HYU 5 BNM 6 WER 7 WER 8 CVC 9 ASD |
Expected Output:
1 2 3 4 5 |
ID Name ----------- ---------- 7 WER 8 CVC 9 ASD |
Create a sample table:
1 2 3 4 5 6 |
CREATE TABLE tbl_TestTable (ID INT, Name VARCHAR(10)) INSERT INTO tbl_TestTable VALUES (1,'ABC'),(2,'XYZ'),(3,'ERZ') ,(4,'HYU'),(5,'BNM'),(6,'WER') ,(7,'WER'),(8,'CVC'),(9,'ASD') |
Solution:
1 2 3 4 5 6 7 |
;WITH CTE AS ( SELECT TOP (SELECT COUNT(1)-3 FROM tbl_TestTable) ID FROM tbl_TestTable ) SELECT * FROM tbl_TestTable WHERE ID NOT IN (SELECT ID FROM CTE) |
Please try the different solution for this puzzle and share it via comment...