简体   繁体   中英

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.

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()

select * from
(Select t.*, RowNumber() over (order by Total desc) as rownum from trytable )
where rownum = 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM