MySQL: GROUP BY within ranges - php

I have a table with scores like this:
score | user
-------------------
2 | Mark
4 | Alex
3 | John
2 | Elliot
10 | Joe
5 | Dude
The table is gigantic in reality and the real scores goes from 1 to 25.
I need this:
range | counts
-------------------
1-2 | 2
3-4 | 2
5-6 | 1
7-8 | 0
9-10 | 1
I've found some MySQL solutions but they seemed to be pretty complex some of them even suggested UNION but performance is very important. As mentioned, the table is huge.
So I thought why don't you simply have a query like this:
SELECT COUNT(*) as counts FROM score_table GROUP BY score
I get this:
score | counts
-------------------
1 | 0
2 | 2
3 | 1
4 | 1
5 | 1
6 | 0
7 | 0
8 | 0
9 | 0
10 | 1
And then with PHP, sum the count of scores of the specific ranges?
Is this even worse for performance or is there a simple solution that I am missing?
Or you could probaly even make a JavaScript solution...

Your solution:
SELECT score, COUNT(*) as counts
FROM score_table
GROUP BY score
ORDER BY score;
However, this will not returns values of 0 for count. Assuming you have examples for all scores, then the full list of scores is not an issue. You just won't get counts of zero.
You can do what you want with something like:
select (case when score between 1 and 2 then '1-2'
when score between 3 and 4 then '3-4'
. . .
end) as scorerange, count(*) as count
from score_table
group by scorerange
order by min(score);
There is no reason to do additional processing in php. This type of query is quite typical for SQL.
EDIT:
According to the MySQL documentation, you can use a column alias in the group by. Here is the exact quote:
An alias can be used in a query select list to give a column a
different name. You can use the alias in GROUP BY, ORDER BY, or HAVING
clauses to refer to the column:

SELECT
SUM(
CASE
WHEN score between 1 and 2
THEN ...

Honestly, I can't tell you if this is faster than passing "SELECT COUNT(*) as counts FROM score_table GROUP BY score" into PHP and letting PHP handle it...but it add a level of flexibility to your setup. Create a three column table as 'group_ID', 'score','range'. insert values into it to get your groupings right
1,1,1-2
1,2,1-2
1,3,3-4
1,4,3-4
etc...
Join to it on score, group by range. THe addition of the 'group_ID' allows you to set groups...maybe have group 1 break it into groups of two, and let a group_ID = 2 be a 5 set range (or whatever you might want).
I find the table use like this is decently fast, requires little code changing, and can readily be added to if you require additional groupings or if the groupings change (if you do the groupings in code, the entire case section needs to be redone to change the groupings slightly).

How about this:
select concat((score + (1 * (score mod 2)))-1,'-',(score + (1 * (score mod 2)))) as score, count(*) from TBL1 group by (score + (1 * (score mod 2)))
You can see it working in this fiddle: http://sqlfiddle.com/#!2/215839/6
For the input
score | user
-------------------
2 | Mark
4 | Alex
3 | John
2 | Elliot
10 | Joe
5 | Dude
It generates this:
range | counts
-------------------
1-2 | 2
3-4 | 2
5-6 | 1
9-10 | 1

If you want a simple solution which is very powerful, add an extra field within your table and put a value in it for the score so 1 and 2 have the value 1, 3 and 4 has 2. With that you can group by that value. Only by inserting the score you've to add an extra field. So your table looks like this:
score | user | range
--------------------------
2 | Mark | 1
4 | Alex | 2
3 | John | 2
2 | Elliot | 1
10 | Joe | 5
5 | Dude | 3
Now you can do:
select count(score),range from table group by range;
This is always faster if you've an application where selecting has prior.
By inserting do this:
$scoreRange = 2;
$range = ceil($score/$scoreRange);

Related

how to query for at least X results with a specific attribute

I am trying to get a certain amount of rows of which another amount of rows satisfy a specific condition.
I'll explain.
table 1:
ID | NAME
1 | Thomas
2 | Jason
3 | Oleg
4 | Matt
5 | Sheldon
6 | Jenny
table 2:
ID | ACTIVE
1 | 1
2 | 0
3 | 1
4 | 1
5 | 0
6 | 1
Query:
SELECT tbl_1.ID, tbl_1.NAME, tbl_2.ACTIVE
FROM tbl_1 JOIN tbl_2 ON
tbl_1.ID = tbl_2.ID
WHERE tbl_2.ACTIVE=1
LIMIT 5
in this example I would like to get a minimum number of 5 users, of which 3 are active.
of course the query above will not do the job right, as it limits the total rows to 5. But 3 of the rows in the result (or less if no more exist) MUST be active.
the other way I can think of getting this done, is a union, but my query is so cumbersome, long and complex.
Any ideas?
Use ORDER BY instead:
SELECT tbl_1.ID, tbl_1.NAME, tbl_2.ACTIVE
FROM tbl_1 JOIN
tbl_2
ON tbl_1.ID = tbl_2.ID
ORDER BY (tbl_2.ACTIVE = 1) DESC
LIMIT 5;
This puts the active users at the top of the list and then fills in the rest with other users.
Note: The ORDER BY clause could simply be ORDER BY tbl_2.ACTIVE DESC. I left the boolean logic so you could see the similarity to the WHERE clause.
The way to at least x results is to use the count aggregate and the keyword having
select f1, count(*) records
from yourTable
where whatever
group by f1
having count(*) > x

SQL Rank of users score, from arbitrary position

Looking around the site, most questions regarding to Ranks in a highscore table assumes that you will be looking at the entire or the top of the table.
In a lot of examples on this site, the rank is found by ordering the items by score and then counting the rows from the top of the set, or counting the items as they are retrived. Like this
score name rank
1000 test345 1
999 test980 2
950 test234 3
833 test291 4
760 test573 5
731 test981 6
In my situation, I need to look at only a portion of the scores, which may not be at the top of the table, for instance, maybe halfway though the leaderboard:
scores name rank
500 test451 43
433 test768 44
425 test120 45
where the user is only shown the scores around his. The part of the leader board the user is looking at above, isn't at the top of the leader board, so I can't count the rows in the returned scores to determine their rank.
How can I determine the rank of user in a leader board at and arbitrary position efficiently, amusing there a lot of entries.
Also this is my first foray into sql and php. I might not be using the correct terminology.
I'm not really sure what you are trying to do. You can limit you result using a LIMIT clause like this:
SELECT * FROM <table> LIMIT 0, 3
Which will only return the first 3 records.
To order the result based on the rank field you would use an ORDER BY clause:
SELECT * FROM <table> ORDER BY rank DESC LIMIT 0, 3
The above query will return 3 records order by rank in descending order.
If you like to calculate the rank based on the scores column this would work:
SELECT scores,
name,
FIND_IN_SET(scores, (SELECT GROUP_CONCAT(scores ORDER BY scores DESC)
FROM <table>)) as rank
FROM <table> ORDER BY rank DESC LIMIT 0, 3;
Running the above query against a table with only two columns scores and name:
+--------+---------+
| scores | name |
+--------+---------+
| 500 | test451 |
| 433 | test768 |
| 425 | test120 |
| 300 | test001 |
| 250 | test002 |
| 200 | test003 |
+--------+---------+
Would yield the following result:
+--------+---------+------+
| scores | name | rank |
+--------+---------+------+
| 500 | test451 | 1 |
| 433 | test768 | 2 |
| 425 | test120 | 3 |
+--------+---------+------+
The GROUP_CONCAT() maximum length is depending on the group_concat_max_len system variable, so for a large table this needs to be changed and I'm not sure this would be the best approach.
Notice that you could/should add indexes to your table to speed things up:
ALTER <table> ADD INDEX `idx_scores` (`scores`);

mysql rank by column value grouped by column value

I am trying to figure out how to rank based on 2 different column numbers in laravel but raw mysql will do. I have a list of videos, these videos are inside of competitions and are given votes if someone likes the video. Each video will have a vote number and a competition number. I am trying to rank based on votes within competition. So for example below I have competition 8, I need the rank of all the videos in that competition based on votes. I then need the same for competition 5 etc.
|rank|votes|competition|
------------------
| 1 | 100 | 8 |
------------------
| 2 | 50 | 8 |
------------------
| 3 | 30 | 5 |
------------------
| 1 | 900 | 5 |
------------------
| 2 | 35 | 5 |
------------------
I have tried various group and selectby methods but nothing seems to work, any ideas?
In Mysql you can use user-defined variables to calculate rank,case statement checks if competition is same as the previous row then increment rank by one if different then assign 1 an order by is needed to have correct rank for the video
SELECT t.*,
#current_rank:= CASE WHEN #current_rank = competition
THEN #video_rank:=#video_rank +1
ELSE #video_rank:=1 END video_rank,
#current_rank:=competition
FROM t ,
(SELECT #video_rank:=0,#current_rank:=0) r
ORDER BY competition desc, votes desc
See Demo
If you are confused with the last extra column you can use a subselect
See Demo
You can use windowing functions:
select
competition, votes, rank() over (partition by competition order by votes desc) as rank
from
table1

Fixture generator in PHP or MySQL

I am trying to generate fixtures for a sports website. I have a table called Members, with relevant columns being member_id and league_id. The league_id will be passed from a form on the previous page as the variable $leagueid.
I'm pulling out all the member ID's relating to that league ID using...
$result = mysql_query("SELECT member_id FROM Members WHERE league_id = '$leagueid'")
I now need to generate fixtures for all these member ID's and then insert that data into the MySQL table 'Fixtures'. Each row of data in that table needs to include:-
player1 - member_id of the first player
player2 - member_id of the second player
week - integer showing which week the match will be played
league_id
However, there are some special conditions that also need to be applied.
Every 3rd week needs to remain free (i.e. weeks 3,6,9,12 etc). No matches can be scheduled on these weeks
There needs to be an option (which will be selected and passed from a form on the previous page as a checkbox variable called $double) which will double up the matches. This means that after generating one complete round of fixtures, you need to take the generated list, swap ID's for players 1 and 2, and duplicate them all. So 1 round of fixtures could look like this....
Week 1
1 vs 2
3 vs 4
Week 2
1 vs 3
2 vs 4
Week 3
1 vs 4
2 vs 3
Then you would swap the ID's and add on another set...
Week 4
2 vs 1
4 vs 3
Week 5
3 vs 1
4 vs 2
Week 6
4 vs 1
3 vs 2
What I'm looking for is some code that will generate all these fixtures while keeping in mind all the special conditions that I've listed.
I know this is all possible in PHP but I also think I can do it using one SQL query instead, which might be a lot cleaner. Can anyone help me out?? Thanks!!
P.S. I know I'm using mysql and not mysqli. I am currently trying to transfer over to mysqli but I'm having some problems which I have posted on a separate question that I have yet to get a correct answer to.
SELECT * FROM ints;
+---+
| i |
+---+
| 0 |
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
| 6 |
| 7 |
| 8 |
| 9 |
+---+
SELECT * FROM ints WHERE MOD(i,3) > 0;
+---+
| i |
+---+
| 1 |
| 2 |
| 4 |
| 5 |
| 7 |
| 8 |
+---+
The second part is simply
INSERT INTO my_table SELECT week_id+3, column_2, column_1 FROM my_table;

Summarize db table player stats on output (multiple entries)

I'm trying to output a "scoreboard"/"standings" list of hockey players. I currently have a MySQL table like this:
statsID | matchID | playerID | goals | assists
120 | 2 | 3 | 4 | 1
121 | 2 | 4 | 2 | 2
122 | 3 | 3 | 0 | 3
So for each match the players gets added along with goals and assists. This means that there's multiple entries (several matches) for each player.
So basically, is there a good way to fetch the player data, summarize goals and assists (+ overall points) and output it in a list?
Right now, I have a basic query just outputting each row (as far as my current knowledge reaches). So how can I just output one entry of each player with his stats summarized?
Here's one approach:
SELECT t.playerID
, SUM(t.goals) AS total_goals
, SUM(t.assists) AS total_assists
FROM sometable t
GROUP BY t.playerID
ORDER BY t.playerID
Not clear what calculation you use for "overall points", if you are just adding goals and assists, then you can use this in the SELECT list:
, SUM(t.goals)+SUM(t.assists) AS overall_points
You need to use a group by clause.
SELECT playerID, SUM(goals + assist) overall points
FROM table_name
GROUP BY playerID

Categories