sql - How to extract second highest row from a table -
i have 4 tables :
- batch(batch_id, batch_start_date, batch_strength, course_id)
- course(course_id, course_name, course_category, course_fees, course_duration)
- enrollment(batch_id, student_id, enrollment_date)
- student(student_id, student_name, student_mail, student_date_of_birth, student_city, student_phone, student_qualification)
now according question have display coursename has 2nd highest revenue collection
according above question here solution
select c.course_name, c.course_fees*count(c.course_name) total_revenue course c join(batch b join enrollment e on b.batch_id=e.batch_id) on c.course_id=b.course_id group c.course_name, c.course_fees order total_revenue desc ;
now problem not able extract second row resulting table above code. how can extract second row above resulting table?(answer specific oracle 11g appreciated)
non-analytic solution fun of it:
with r ( select min(c.course_name) course_name, min(c.course_fees) * count(*) revenue course c inner join batch b on b.course_id = c.course_id inner join enrollment e on e.batch_id = b.batch_id group c.course_id ) select course_name, revenue r revenue = (select max(revenue) r revenue < (select max(revenue) r))
this handles ties (in both first , second place.) i'm going out on limb , assuming intended group course_id
. looks more class exercise don't expect there's complication historical fee information or going on.
edit based on comment below sounds may have multiple courses same name , different fees. suspect original query not work correctly since grouping on course_fees
.
notice change below uses grouping on course_name
, summation on course_fees
:
with r ( select course_name, sum(c.course_fees) revenue course c inner join batch b on b.course_id = c.course_id inner join enrollment e on e.batch_id = b.batch_id group c.course_name ) select course_name, revenue r revenue = (select max(revenue) r revenue < (select max(revenue) r))
Comments
Post a Comment