Reputation:
I have a table containing player name
, total on court
time, and date
of that game.
Given a list of players, I want to calculate the average on court time of each player in recent 5 games.
This is how I get average on court time of Aaron Brooks.
select `Player Name`, AVG(TIME_TO_SEC(`Total on Court`))
from
(SELECT * FROM nba.`player stat total`
where `Player Name`='Aaron Brooks'
order by `date` desc
limit 5) as t
But I have a list of players, it is possible to do in pure sql rather than executing sql in a for-loop in my program?
The players may be in the form ('Aaron Brooks', 'Chris Bosh', 'Andre Miller')
or any other form you like.
Upvotes: 1
Views: 615
Reputation: 64466
You can use user-defined variables to get 5 recent records per player group
SELECT t.`Player Name` ,
AVG(TIME_TO_SEC(t.`Total on Court`))
FROM (
SELECT s.*,
@rank:= CASE WHEN @group = s.`Player Name` THEN @rank +1 ELSE 1 END rank ,
@group:= s.`Player Name` g
FROM
`player stat total` s
JOIN (SELECT @group:='',@rank:='') t
WHERE s.`Player Name` IN('Aaron Brooks', 'Chris Bosh', 'Andre Miller')
ORDER BY `Player Name` ,`date` DESC
) t WHERE t.rank <=5
GROUP BY t.`Player Name`
Upvotes: 0
Reputation: 1082
Give this a try
SELECT *
FROM
(SELECT `Player Name`, SUM(AVG(TIME_TO_SEC(`Total on Court`))) AS Avg FROM nba.`player stat total`
GROUP BY `Player Name`
ORDER BY `date` desc
LIMIT 5) AS t
Upvotes: 0