Top, bottom, and average statements for SQL queries
We're going to use it as an example of student achievement.
/*
Structure
Student table
Student (s#,sname,sage,ssex)--s# student number, sname student name, Sage birth date, ssex student gender
--2. Timetable
Course (c#,cname,t#)--c#--course number, Cname course name, t# teacher number
*/
The highest score, lowest score and average score of each section are shown: Course ID, course name, highest score, lowest score, average score, pass rate, medium rate, good rate, excellent rate
--Pass for >=60, medium for: 70-80, excellent as: 80-90, excellent for: >=90
--Method 1
Select m.c# [Course number], M.cname [course name],
Max (N.score) [Highest score],
Min (n.score) [Lowest score],
Cast (AVG (N.score) as Decimal (18,2)) [Average score],
Cast ((select count (1) from SC where C # = m.c# and score >=) *100.0/(select COUNT (1) from SC where C # = m.c#) as Dec iMAL (18,2)) [Pass rate (%)],
Cast ((select count (1) from SC where C # = m.c# and score >= and score <) *100.0/(select COUNT (1) from SC wher E C # = m.c#) as decimal (18,2)) [Medium rate (%)],
Cast ((select count (1) from SC where C # = m.c# and score >= and score <) *100.0/(select COUNT (1) from SC wher E C # = m.c# as Decimal (18,2)) [Good rate (%)],
Cast ((select count (1) from SC where C # = m.c# and score >=) *100.0/(select COUNT (1) from SC where C # = m.c#) as Dec iMAL (18,2)) [excellent rate (%)]
From Course m, SC N
where m.c# = n.c#
Group BY m.c#, M.cname
ORDER BY m.c#
--Method 2
Select m.c# [Course number], M.cname [course name],
(select Max (score) from SC where C # = m.c#) [Highest score],
(select min (score) from SC where C # = m.c#) [Lowest score],
(Select CAST (AVG (score) as decimal (18,2) from SC where C # = m.c#) [Average score],
Cast ((select count (1) from SC where C # = m.c# and score >=) *100.0/(select COUNT (1) from SC where C # = m.c#) as Dec iMAL (18,2)) [Pass rate (%)],
Cast ((select count (1) from SC where C # = m.c# and score >= and score <) *100.0/(select COUNT (1) from SC wher E C # = m.c#) as decimal (18,2)) [Medium rate (%)],
Cast ((select count (1) from SC where C # = m.c# and score >= and score <) *100.0/(select COUNT (1) from SC wher E C # = m.c# as Decimal (18,2)) [Good rate (%)],
Cast ((select count (1) from SC where C # = m.c# and score >=) *100.0/(select COUNT (1) from SC where C # = m.c#) as Dec iMAL (18,2)) [excellent rate (%)]
From Course m
ORDER BY m.c#