2016-03-14 58 views
-2

我想要表中的最后五条记录。条件是列包含重复值和空值。从表中获取最后五条记录

CREATE TABLE [dbo].[Student] (
    [Student_Name] [VARCHAR](50) NULL 
) 

INSERT INTO Student 
VALUES 
     ('Mukesh') 
    , ('Vinod') 
    , ('Mukesh') 
    , (NULL) 
    , ('Shree') 
    , ('Raj') 
    , (NULL) 
    , ('Abhijit') 
    , ('Raju') 
    , ('Sharon') 
    , ('Ashok') 
    , ('Meena') 
    , ('Mukesh') 
    , (NULL) 

SELECT * FROM Student 

enter image description here

注:我想最近五个记录从上面的表

结果这样的: enter image description here

+4

你是如何定义的最后一个记录? –

+1

如果没有明确的'ORDER BY'子句,结果集的顺序将不能保证。所以除非你指定哪一列定义_last records_,否则你在这里得到的答案将不准确。 –

+0

最后一条记录是整行数据的最后一行 – Surendra

回答

1
DECLARE @Student TABLE (Student_Name VARCHAR(50)) 

INSERT INTO @Student 
VALUES 
     ('Mukesh'), ('Vinod'), ('Mukesh'), (NULL) 
    , ('Shree'), ('Raj'), (NULL), ('Abhijit'), ('Raju') 
    , ('Sharon'), ('Ashok'), ('Meena'), ('Mukesh'), (NULL) 

SELECT TOP(5) Student_Name 
FROM (
    SELECT *, rn = ROW_NUMBER() OVER (ORDER BY 1/0) 
    FROM @Student 
) t 
ORDER BY rn DESC 
+3

这不保证始终返回相同的结果。 – FLICKER

+0

@FLICKER我知道......但是没有'PK',OP会有什么期待...... – Devart

+2

downvote原因:什么闪烁写道。 –

-4

使用DISTINCT从结果集删除重复。 例如:

SELECT DISTINCT expressions 
FROM tables 
[WHERE conditions]; 

和使用LIMIT来限制结果数

+5

'LIMIT'是**不**是** Microsoft SQL Server **或标准ANSI/ISO SQL中的有效关键字/操作 - –

0
declare @c int 
set @c = (select COUNT(*) from Student) 
select * 
from 
(select ROW_NUMBER() over (order by student_id) as row, * 
from Student) t 
where t.row between (@c-5) and @c 

试试这一个。

更新:

declare @c int 
set @c = (select COUNT(*) from Student) 
select * 
from 
(select ROW_NUMBER() over(order by (select 1)) as row, * 
from Student) t 
where t.row between (@c-5) and @c 
+0

不工作。我没有student_id学生表中的列 – Surendra

+0

更新新的查询:) – ThanhPT

+0

谢谢....这也是可行的。 – Surendra

相关问题