简体   繁体   中英

Ordering an SQL query using returned results from a sub query

Hey i am trying to order an SQL query using returned results from a sub query ie

SELECT tb1.stud_id , tb1.stud_name , (SELECT sum(score) FROM scores WHERE student_id = tb1.
student) AS total_marks 
FROM Students_info AS tb1
GROUP BY tb1.stud_id , tb1.stud_name
ORDER BY total_marks DESC

I have also tried

ORDER BY (SELECT sum(score) FROM scores WHERE student_id = tb1.student) DESC

Assistance on this would be greatly appreciated.

I'm confused by your query, the select statement you are ordering by will return the same results for every student, because it's not related to the students_info table.

I assume you want something like this:

SELECT tb1.stud_id , tb1.stud_name , SUM(tb2.score) AS total_marks
FROM Students_info AS tb1
LEFT JOIN scores AS tb2
    ON tb1.stud_id = tb2.student_id
GROUP BY tb1.stud_id , tb1.stud_name
ORDER BY total_marks DESC

I found nothing wrong with your query. Try this sql. It will work.

SELECT tb1.stud_id , tb1.stud_name , sum(tb2.score) AS total_marks 
FROM Students_info AS tb1
LEFT JOIN scores AS tb2
ON tb1.student_id=tb2.student_id
GROUP BY tb1.stud_id , tb1.stud_name
ORDER BY sum(tb2.score) DESC

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM