如何在学生表中选择一个学科的最高分和另一学科的最低分?

时间:2018-10-18 13:52:32

标签: sql sql-server

从数学学科中选择最高分,然后从物理学科中选择最低分。

我只能这样想:

Select subject, max(Marks) as Max_Marks, MIN(Marks) as Min_Marks
from Student 
group by Subject

但是上面的查询显示每个主题的最大,最小。

还有其他查询方式吗?

4 个答案:

答案 0 :(得分:1)

只需包含{ "name": "new-home", "version": "0.1.0", "private": true, "homepage" : "home/newHome/build", "dependencies": { "@types/react-slick": "^0.23.2", "react": "^16.5.2", "react-dom": "^16.5.2", "react-scripts": "1.1.5", "react-slick": "^0.23.1", "reactstrap": "^6.5.0", "slick-carousel": "^1.8.1" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test --env=jsdom", "eject": "react-scripts eject" } } 子句并进行条件聚合:

WHERE

答案 1 :(得分:1)

以上三个答案是正确的。 这种方式可能更容易理解

SELECT 
  (SELECT max(Marks) from Student WHERE subject = 'math')    AS Max_Math
, (SELECT min(Marks) from Student WHERE subject = 'physics') AS Min_Physics;

答案 2 :(得分:0)

您可以使用以下带有where子句的查询,并使用case-when语句来决定是否需要使用max或min函数。

Select subject, mark = (case when subject = 'math' then max(Marks) else min(Marks) end)
from Student 
where Subject = 'math'
   or Subject = 'physics'
group by Subject

答案 3 :(得分:0)

根据您的条件添加WHERE

查询:

CREATE TABLE #temp(SUBJECT varchar(12), MARK int)
INSERT INTO #temp(SUBJECT, MARK)
select 'Maths',   100  union
select 'Maths',   90  union
select 'Maths',   40  union
select 'Physics',   60  union
select 'Physics',   30  union
select 'Physics',   20  

Select subject, max(Mark) as Max_Marks, MIN(Mark) as Min_Marks
from #temp 
where Subject in ('maths','physics')
group by Subject

输出:

enter image description here