sql - How to 'add' a column to a query result while the query contains aggregate function? -


i have table named 'attendance' used record student attendance time in courses. table has 4 columns, 'id', 'course_id', 'attendance_time', , 'student_name'. example of few records in table is:

23    100    1/1/2010 10:00:00    tom

24    100    1/1/2010 10:20:00    bob

25    187    1/2/2010 08:01:01    lisa

.....

i want create summary of latest attendance time each course. created query below:

select course_id, max(attendance_time) attendance group course_id 

the result this

100    1/1/2010 10:20:00

187    1/2/2010 08:01:01

now, want add 'id' column result above. how it?

i can't change command this

select id, course_id, max(attendance_time) attendance group id, course_id 

because return records if aggregate function not used. please me.

this typical 'greatest per group', 'greatest-n-per-group' or 'groupwise maximum' query comes on stack overflow every day. can search stack overflow these terms find many different examples of how solve different databases. 1 way solve follows:

select     t2.course_id,     t2.attendance_time     t2.id (     select         course_id,         max(attendance_time) attendance_time     attendance     group course_id ) t1 join attendance t2 on t1.course_id = t2.course_id , t1.attendance_time = t2.attendance_time 

note query can in theory return multiple rows per course_id if there multiple rows same attendance_time. if cannot happen don't need worry issue. if potential problem can solve adding grouping on course_id, attendance_time , selecting minimum or maximum id.


Comments

Popular posts from this blog

c++ - How do I get a multi line tooltip in MFC -

asp.net - In javascript how to find the height and width -

c# - DataTable to EnumerableRowCollection -