开发者

Counting biggest values within a certain period of time

开发者 https://www.devze.com 2023-02-05 11:27 出处:网络
I need help with the following query, I will post an example of the table. player | goals | gamedate playername1 |1| 2011-01-01

I need help with the following query, I will post an example of the table.

     player | goals | gamedate

playername1 |  1    | 2011-01-01
playername2 |  2    | 2011-01-01
playername1 |  1    | 2011-01-02
playername3 |  1    | 2011-01-01
playername1 |  2    | 2011-01-03
playername1 |  1    | 2011-01-01
playername3 |  1    | 2011-01-01
playername2 |  2    | 2011-01-01
playername1 |  1    | 2011-01-04

There's a lot more data like that I was wondering how can I write a query that will give the top players with most goals between a certain period of time (game season)?

Edit: It seems I was mista开发者_开发问答ken in the way the data was structured. I'm sorry for this. I will leave the previous table so that everyone can see the first answer to. I didn't want to open a new question since it is essentially the same thing. My apologiies Haim.

`table1`
  id | gamedate

1    | 2011-01-01
2    | 2011-01-02
3    | 2011-01-03
4    | 2011-01-04
5    | 2011-01-05


`table2`
id | gameid  |      player | goals

 1 |   1     |  playername1 |  1  
 2 |   1     |  playername2 |  2  
 3 |   2     |  playername1 |  1 
 4 |   1     |  playername3 |  1
 5 |   3     |  playername1 |  2
 6 |   4     |  playername1 |  1
 7 |   2     |  playername3 |  1
 8 |   3     |  playername2 |  2
 9 |   5     |  playername1 |  1

Where gameid is a foreign key that's referenced by ID in table1.


replace the date you want to check , and set the limit (in the example is 5) to how many players you want.

SELECT player , sum(goals) AS top_scores FROM mytable 
WHERE gamedate BETWEEN '2011-01-02' AND '2011-01-07'
GROUP BY player ORDER BY top_scores DESC  LIMIT 5

EDIT (according to edit of question , all you need is to add a join):

SELECT player , sum(goals) AS top_scores FROM table2 t2
LEFT JOIN table1 t1  ON t1.id = t2.gameid
WHERE gamedate BETWEEN '2011-01-02' AND '2011-01-07'
GROUP BY player ORDER BY top_scores DESC  LIMIT 5
0

精彩评论

暂无评论...
验证码 换一张
取 消