[英]How to get the 2nd highest from a table where it need to be added first in sql server in a single query?
I was asked this question in an interview, this the table 面试中有人问我这个问题,这张桌子
Roll | Sub | Marks
1 A 20
1 B 21
2 A 15
2 B 19
3 A 21
3 B 22
now i have to find the roll and marks 2nd highest marks obtained by the student 现在我必须找到该卷并获得该学生获得的第二高分
so i answered this : 所以我回答了这个:
declare @trytable table
(
roll int,
total int
)
insert @trytable
select Roll, SUM(Marks)
from Student
group by Roll
Select *
from @trytable t
where t.total in (select MAX(total) from @trytable where total not in ( select
MAX(total) from @trytable))
which is giving the correct answer but the interviewer wanted this to be done in single query by not using the table variable 这给出了正确的答案,但访问员希望通过不使用表变量在单个查询中完成此操作
the result should be 结果应该是
Roll | Total Marks
1 41
so how can i do that ... please let me know 所以我该怎么做...请让我知道
Below query gives the roll numbers who obtained 2nd highest marks summing the two subject marks. 下面的查询给出了将两个主题标记相加得出的第二高分的卷数。
SELECT TOP 1 Roll, Marks
FROM
(
SELECT DISTINCT TOP 2 Roll,
SUM(Marks) over (Partition by Roll) Marks
FROM
YourTable
ORDER BY marks DESC
) temp
ORDER BY Marks
OR 要么
SELECT
DISTINCT Roll,
Marks,
SRANK
FROM
(
SELECT
Roll,
Marks,
DENSE_RANK() OVER( ORDER BY Marks DESC) AS SRANK
FROM
(
SELECT
Roll,
SUM(Marks) over (Partition by Roll) Marks
FROM YourTable
)x
)x
WHERE SRANK=2
If I understand you correctly, you just want to get the total score for the second highest student, and student is identified by roll? 如果我对您的理解正确,那么您只想获取第二高的学生的总成绩,而该学生是否按成绩进行识别? If so: 如果是这样的话:
select roll, sum(Marks) from Student group by roll order by total limit 1,1;
Not 100% sure about the 1,1 - what you are saying is, I only want 1 row, and not the first. 不是100%知道1,1-您所说的是,我只想要1行,而不是第一行。
It can also be done through simple query: 也可以通过简单的查询来完成:
select Marks from trytable where N = (select count(distinct Marks) from trytable b where a.Marks <= b.Marks)
where N = any value
Or 要么
SELECT Roll,Marks
FROM tableName WHERE Marks =
(SELECT MIN(Marks ) FROM
(SELECT TOP (2) Marks
FROM tableName
ORDER BY Marks DESC) )
You can use analytic functions like RowNumber() 您可以使用RowNumber()之类的分析函数
select * from
(Select t.*, RowNumber() over (order by Total desc) as rownum from trytable )
where rownum = 2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.