I am working on a MYSQL, and I am looking for a solution to show data grouping by ratio.
I have a COURSE
table which contain courses id and courses ratio. I have another table, ASK
, which contain askers id, and another field course id pointing on COURSE
table (ids correspond). With one SQL query, I would like to display all asks grouping by ratio and rejecting other demands. Demands are considered by seniority list.
By example, I have 3 courses: the first one allow only 2 people and 2 other courses allow only one person. In the ASK table, we have 3 askers (JACK, JOE AND JOHN) pointing on first course, (JOHN AND JOE) 2 on second and third (JACK AND JOHN). JACK is the older, after its JOHN and after its JOE.
I would like to see:
course id studentName
-------------------------
1 JACK
1 JOHN 开发者_运维知识库
2 JOHN
3 JACK
SELECT c.courseID
s.studentName
FROM course AS c
JOIN asks AS a
ON a.courseID = c.courseID
JOIN student AS s
ON s.studentName = a.studentName
JOIN asks AS a2
ON a2.courseID = c.courseID
JOIN student AS s2
ON s2.studentName = a2.studentName
AND s2.seniority <= s.seniority
GROUP BY c.courseID
, c.ratio
, s.studentName
HAVING c.ratio >= COUNT(*)
ORDER BY c.courseID
, s.seniority
精彩评论