MySQL query data subjects of the first three

 

 

 

 method one:

SELECT sc.*,c.`
Cname` ,COUNT(sc.C)
FROM sc
LEFT JOIN sc a
ON sc.C = a.C AND sc.score >= a.score
LEFT JOIN course c
ON sc.C = c.C
WHERE sc.C = c.C
GROUP BY
sc.C,sc.S,sc.score
HAVING COUNT(sc.C)>=4
ORDER BY a.C,a.score DESC

Resolution:

Sc copy data to a table, compared with the original sc. Each score is greater than the other count statistics data. Press sc.C, sc.S group

SELECT sc.* ,COUNT(sc.C) 
FROM sc  
LEFT JOIN sc a
ON sc.C = a.C AND sc.score >= a.score
GROUP BY sc.C,sc.S

 

 You can see, count the count first row of data is 6, because we want to take the top three for each subject, sc table total student S No. 7,

Itself is not included in counting the count, compared to 6 needs to be removed before the count value greater than 3 3-- .

SELECT sc.* ,COUNT(sc.C) 
FROM sc  
LEFT JOIN sc a
ON sc.C = a.C AND sc.score >= a.score
GROUP BY
sc.C,sc.S,sc.score
HAVING COUNT(sc.C)>3
ORDER BY a.C,a.score DESC

方法二:

SELECT a.* FROM
sc a
WHERE
(SELECT COUNT(*)
FROM sc
WHERE sc.C =a.C
AND a.score<sc.score) <3
ORDER BY a.C,a.score DESC

解析:

与方法一同理,复制一个表进行count计数

Guess you like

Origin www.cnblogs.com/jescs/p/12186019.html