1

我在一次采访中被问到这个问题,这张桌子

Roll | Sub | Marks
 1      A     20
 1      B     21
 2      A     15
 2      B     19
 3      A     21
 3      B     22

现在我必须找到学生获得的卷和分数第二高的分数

所以我回答了这个:

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

这是给出正确答案但面试官希望通过不使用表变量在单个查询中完成

结果应该是

 Roll | Total Marks
  1        41

那我该怎么做……请告诉我

4

4 回答 4

2

下面的查询给出了获得第二高分的卷号,将两个科目分数相加。

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 

或者

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
于 2013-09-21T06:36:53.183 回答
0

如果我理解正确,您只想获得第二高学生的总分,而学生是通过roll来识别的?如果是这样:

select roll, sum(Marks) from Student group by roll order by total limit 1,1;

不是 100% 确定 1,1 - 你说的是,我只想要 1 行,而不是第一行。

于 2013-09-21T06:31:11.447 回答
0

也可以通过简单的查询来完成:

select Marks from trytable where N = (select count(distinct Marks) from trytable b where a.Marks <= b.Marks)
where N = any value

或者

SELECT Roll,Marks 
FROM tableName WHERE Marks =
       (SELECT MIN(Marks ) FROM 
             (SELECT TOP (2) Marks 
              FROM tableName 
              ORDER BY Marks DESC) )
于 2013-09-21T06:32:15.193 回答
0

您可以使用 RowNumber() 等分析函数

select * from
(Select t.*, RowNumber() over (order by Total desc) as rownum from trytable )
where rownum = 2
于 2013-09-21T06:50:35.837 回答