如何在单个查询中选择数据?

时间:2013-07-26 10:45:10

标签: sql-server sql-server-2008

希望你们一切顺利 我有这样的问题。 一班学生参加了考试。 现在我想选择前3位置持有者获得最高分。 现在的情况是......如果有两个学生得到100分,一个得到99分,一个得到98分,那么四个学生就是前三个职位

Student1 = 100 marks at first position
Student2 = 100 marks at first position
Student3 = 99 marks at second position
Student4 = 98 marks at thirs position

我怎样才能让这四名学生获得前三个职位 如果我使用查询 通过MonthlyPremium desc从被保险人的订单中选择前3个MonthlyPremium 然后它重新排列前3行,即

Student1 = 100 marks (who is at first position)
Student2 = 100 marks (who is at first position)
Student3 = 99 marks (who is at second position)
while the student4 = 98 at third poistion is missing.

任何机构都可以告诉我选择所有这些学生的正确查询。 感谢

3 个答案:

答案 0 :(得分:5)

Select Student,Marks,Rank from (
Select Student,
       Marks,
       Dense_Rank() Over(Order by Marks Desc) as Rank from TableName
    )t 
     where t.Rank<4 

答案 1 :(得分:0)

尝试这样的事情(我不确定sql的正确性):

select * from students where students.mark in (select mark from students order by mark DESC LIMIT 3)

此查询需要3个最高分,而不是只带有此标记的学生

答案 2 :(得分:0)

 CREATE TABLE BookTitle (
 Id INT NOT NULL,
 NAME VARCHAR(60) NULL,
 Marks INT null
 )
 INSERT INTO BookTitle VALUES (1,'s',100) ,(2,'d',100) ,(3,'e',99),(4,'f',98)

SELECT B.* FROM BookTitle B WHERE 3>=(SELECT COUNT(DISTINCT (A.Marks)) FROM  BookTitle A WHERE A.marks >=B.Marks)