Reputation: 3
Select max marks from math subject and select min marks from physics subject.
I can only think of it like following:
Select subject, max(Marks) as Max_Marks, MIN(Marks) as Min_Marks
from Student
group by Subject
But above query shows max, min for each subject.
Any other way to query this ?
Upvotes: 0
Views: 7755
Reputation: 341
Above three answers are correct. This way may be easier understand
SELECT
(SELECT max(Marks) from Student WHERE subject = 'math') AS Max_Math
, (SELECT min(Marks) from Student WHERE subject = 'physics') AS Min_Physics;
Upvotes: 1
Reputation: 1658
Add WHERE
with your condition
Query:
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
Output:
Upvotes: 0
Reputation: 50163
Just include WHERE
clause & do conditional aggregation :
select max(case when Subject = 'math' then Marks end) as math_Max_Marks,
min(case when Subject = 'physics' then Marks end) as physics_Min_Marks
from Student
where Subject in ('math', 'physics');
Upvotes: 1
Reputation: 7960
You can use a query like below, with a where clause and use a case-when statement to decide whether you need to use max or min function.
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
Upvotes: 0