Reputation: 699
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
Upvotes: 1
Views: 1668
Reputation: 1064
You can use analytic functions like RowNumber()
select * from
(Select t.*, RowNumber() over (order by Total desc) as rownum from trytable )
where rownum = 2
Upvotes: 0
Reputation: 18629
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
Upvotes: 2
Reputation: 8626
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) )
Upvotes: 0
Reputation: 2982
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.
Upvotes: 0