繁体   English   中英

如何从需要在单个查询中首先添加到sql server中的表中获得第二高的表?

[英]How to get the 2nd highest from a table where it need to be added first in sql server in a single query?

面试中有人问我这个问题,这张桌子

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

所以我该怎么做...请让我知道

下面的查询给出了将两个主题标记相加得出的第二高分的卷数。

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

如果我对您的理解正确,那么您只想获取第二高的学生的总成绩,而该学生是否按成绩进行识别? 如果是这样的话:

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

不是100%知道1,1-您所说的是,我只想要1行,而不是第一行。

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

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

您可以使用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.

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