![](/img/trans.png)
[英]How to get the Highest, then the lowest, then the 2nd higest, and then the 2nd lowest value and so on from a table
[英]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.