postgresql - Sort by aggregate value in sql -
let's have following student data:
classroom gender student_id ------------------------------------- first grade m 123 first grade f 124 first grade f 125 second grade m 126 third grade m 127 ...
i want produce following result: top 3 biggest classrooms ordered total number of students detail each:
classroom boys_count girls_count total_count -------------------------------------------------- third grade 30 30 60 first grade 20 5 25 fourth grade 10 10 20
how can in sql ? if necessary, can use specific postrges features.
what tried far:
select count(*) total_count , gender , classroom order 1 group classroom, gender limit 3
then re-organise results in scripting language. slow. want have correct results 1 query
select classroom name, sum(case when gender = 'm' 1 else 0 end) boys_count, sum(case when gender = 'f' 1 else 0 end) girls_count, count(*) total_count your_table group classroom order count(*) desc limit 3
Comments
Post a Comment