MySQL Forums
Forum List  »  Newbie

Re: Need help calculating AVG scores
Posted by: Peter Brawley
Date: August 10, 2007 04:21AM

The median per team is the value >= 50% of values for that team and <= 50% of values for that team, so the quickest route is to save the team medians to a temp table, then aggregate on a join that selects values above the medians:
DROP TABLE IF EXISTS medians;
CREATE TABLE medians
SELECT p1.teamid, AVG(P1.score) AS median
FROM game_sessions AS P1, game_sessions AS P2
WHERE p1.teamid=p2.teamid
GROUP BY p1.teamid
HAVING (
  SUM(CASE WHEN P2.score <= P1.score THEN 1 ELSE 0 END) >= ((COUNT(*) + 1) / 2)
  AND 
  SUM(CASE WHEN P2.score >= P1.score THEN 1 ELSE 0 END) >= (COUNT(*)/2 + 1)
)
OR (
  SUM(CASE WHEN P2.score >= P1.score THEN 1 ELSE 0 END) >= ((COUNT(*) + 1) / 2)
  AND 
  SUM(CASE WHEN P2.score <= P1.score THEN 1 ELSE 0 END) >= (COUNT(*)/2 + 1)
);

SELECT g.teamid, AVG(g.score) AS Top50Avg
FROM game_sessions g
JOIN medians m ON g.teamid = m.teamid AND g.score >= m.median
GROUP BY g.teamid
ORDER BY Top50Avg DESC;

DROP TABLE medians;
PB

Options: ReplyQuote


Subject
Written By
Posted
Re: Need help calculating AVG scores
August 10, 2007 04:21AM


Sorry, you can't reply to this topic. It has been closed.

Content reproduced on this site is the property of the respective copyright holders. It is not reviewed in advance by Oracle and does not necessarily represent the opinion of Oracle or any other party.