An interesting SQL query CHALLENGE: A table named athelets consisting of id, ath_id, name, score, date. +----+--------+-----------------+--------+------------+ | id | ath_id | name | record | r_date | +----+--------+-----------------+--------+------------+ | 1 | 2 | John Wayne | 79 | 2010-07-08 | | 2 | 7 | Ronald Regan | 51 | 2000-03-22 | | 3 | 1 | Ford Harrison | 85 | 2009-11-13 | | 4 | 2 | John Wayne | 69 | 2017-01-01 | Please write a sql query to list the average value of the top three scores of each athlete, something like: ath_id: 1, the arithmetic mean of his/her top 3 records: 77 ath_id: 2, the arithmetic mean of his/her top 3 records: 73 ath_id: 3, the arithmetic mean of his/her top 3 records: 47
答案 0 :(得分:0)
SELECT p.id
,coalesce(c.comment_count,0) as comment_count
,coalesce(f.favorite_count,0) as favorite_count
FROM post p
LEFT JOIN (select post_id,count(*) as comment_count
from comment group by post_id) c ON c.post_id=p.id
LEFT JOIN (select post_id,count(*) as favorite_count
from favourite group by post_id) f ON f.post_id=p.id
上述查询应该按预期工作。
答案 1 :(得分:0)
假设运动员和记录的组合是独一无二的......
SELECT ath_id
, ROUND(AVG(record),2) top3_avg
FROM
( SELECT x.*
FROM athletes x
JOIN athletes y
ON y.ath_id = x.ath_id
AND y.record >= x.record
GROUP
BY x.id
HAVING COUNT(*) <=3
) a
GROUP
BY ath_id;