sql - Need to select different column for a query which requires group by clause -


i have student table contains following columns:

studentname, startyear, endyear, classid, more columns

this table contains startyear , endyear students of different class.

i want write query find students name took maximum years (diff b/w endyear , startyear) pass class.

i want following 3 fields in select query

select studentname, classid,  max(endyear- startyear) maxyears students group classid; 

but group doesn't contains studentname hence query fails(and make sense too).

then : putting result of following query in temp table temp:

select classid,  max(endyear- startyear) students group classid 

and join temp table student table.

select studentname, classid, endyear- startyear student s join temp t on s.classid = t.classid , (s.endyear- s.startyear) = t.maxyears  

but doesn't optimal me. wondering other ways .

try query, self-join fetch row maximum (endyear- startyear):

select s1.studentname, s1.classid, s1.endyear-s1.startyear  student s1 inner join  ( select classid, max(endyear- startyear) students  group classid ) s2 on s1.classid = s2.classid; 

Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

jsf - How to ajax update an item in the footer of a PrimeFaces dataTable? -

django - CSRF verification failed. Request aborted. CSRF cookie not set -