我有下表
Name | Subject | Marks
--------------------------
a M 20
b M 25
c M 30
d C 44
e C 45
f C 46
g H 20
这里我有一个“学生”表,我想获取获得的学生的姓名
学生表中每个科目的最高分数,如下输出。
Name | Subject | Marks
c M 30
f c 46
g h 20
您可以使用 ROW_NUMBER 函数仅返回每个主题的“最佳”行:
MS SQL Server 2008 架构设置:
CREATE TABLE Student
([Name] varchar(1), [Subject] varchar(1), [Marks] int)
;
INSERT INTO Student
([Name], [Subject], [Marks])
VALUES
('a', 'M', 20),
('b', 'M', 25),
('c', 'M', 30),
('d', 'C', 44),
('e', 'C', 45),
('f', 'C', 46),
('g', 'H', 20)
;
查询1:
SELECT Name, Subject, Marks
FROM(
SELECT *, ROW_NUMBER()OVER(PARTITION BY Subject ORDER BY Marks DESC) rn
FROM dbo.Student
)X
WHERE rn = 1
结果:
| NAME | SUBJECT | MARKS |
--------------------------
| f | C | 46 |
| g | H | 20 |
| c | M | 30 |
您也可以使用其他函数和cte来获得结果..
例如:1
select B.Name,
A.Subject,
B.Marks
from ( select Subject,
max(Marks) as High_Marks
from Student
group by Subject
) a
join Student b
on a.subject = b.subject
and a.high_Marks = b.Marks
例如:2:使用cte和dense_rank函数
;WITH cte
AS
(
SELECT
[Name],
[Subject],
[Marks],
dense_rank() over(partition BY [Subject] order by [Marks] DESC) AS Rank
FROM Student
)
SELECT * FROM cte WHERE Rank = 1;
这个基本查询应该适合您的要求。
SELECT Name, Subject, Max(Marks)
FROM Student
GROUP by Subject;
中尝试过
注意:使用SQLite进行检查
SQL> with cte as
2 (
3 select name, subject, marks, dense_rank() over (partition by subject order
by marks desc) rnk
4 from student)
5 select name, subject, marks
6 from cte
7 where rnk=1;
N S MARKS
- - ----------
f c 46
c m 30
SQL>
SELECT
Max(名称)作为名称,主题,Max(标记)作为标记FROM
学生group by
主题类似的问题:
编写一个查询来显示每个科目获得最高分的学生姓名,并按科目名称升序排列。
如果有多个礼帽,请按字母顺序显示他们的名字。
显示为subject_name 和student_name。
O/P:
此问题的解决方案:
SELECT subject_name,student_name
from Student s
inner join Mark m on s.student_id=m.student_id
inner join Subject su on m.subject_id=su.subject_id
inner join (select subject_id
,max(value) as maximum
from Mark ma group by subject_id
) highmarks
ON highmarks.subject_id=m.subject_id
AND highmarks.maximum=m.value
order by subject_name,student_name;
以下查询将完美运行:
select subject_name,student_name from student
inner join mark m using(student_id)
inner join subject su using(subject_id)
inner join (select subject_id,max(value) as maximum from mark m group by subject_id)
highestmark using(subject_id) where highestmark.maximum = m.value
order by subject_name,student_name;
此查询将起作用
select name,subject,marks from stud where marks in (select max(marks) from stud group by subject) ;
通过使用 GROUP BY 和having子句,为您提供简单的sql查询来查找每个主题的最高分
SELECT Name, Subject, Marks from Student GROUP BY (Subject) HAVING Marks=max(Marks);
从学生中选择 *,其中分数 >= (来自学生的分数,其中主题 = 学生.主题);