从表中获取最后五条记录

时间:2016-03-14 07:17:24

标签: sql-server

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

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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分:-4)

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

SELECT DISTINCT expressions
FROM tables
[WHERE conditions];

并使用LIMIT限制结果计数