Group by steps

From Hashmysql
Jump to: navigation, search

DDL:

DROP TABLE IF EXISTS game_result;
CREATE TABLE game_result (
	  game_id INT UNSIGNED		NOT NULL DEFAULT 0
	, username VARCHAR( 20 )	NOT NULL DEFAULT ' '
   	, score INT 			NOT NULL DEFAULT -1	COMMENT 'Assumes a game score must be positive or zero'
) ENGINE=InnoDB
;

DATA:

INSERT INTO game_result (game_id, score, username) VALUES(1, 1, 'xxxx');
INSERT INTO game_result (game_id, score, username) VALUES(3, 16, 'fdsfds');
INSERT INTO game_result (game_id, score, username) VALUES(4, 46, 'weqw');
INSERT INTO game_result (game_id, score, username) VALUES(5, 12, 'eqweq');
INSERT INTO game_result (game_id, score, username) VALUES(10, 82, 'dad');
INSERT INTO game_result (game_id, score, username) VALUES(14, 1, 'dsdas');
INSERT INTO game_result (game_id, score, username) VALUES(15, 120, 'cxzcxz');
INSERT INTO game_result (game_id, score, username) VALUES(29, 71, 'gdfgfd');
INSERT INTO game_result (game_id, score, username) VALUES(321, 93, 'fdsfs');
INSERT INTO game_result (game_id, score, username) VALUES(90, 151, 'cxzvxcvxccxz');

SQL:

SET @chunk = 50;
SELECT 
	  CONCAT( FLOOR(score / @chunk ) * @chunk, '-', CEIL( score / @chunk ) * @chunk - 1) AS val_range
	, COUNT( score ) AS score_count
FROM
	game_result
GROUP BY 
	FLOOR( score / @chunk )
;


Result:

+-----------+-------------+
| val_range | score_count |
+-----------+-------------+
| 0-49      |           5 |
| 50-99     |           3 |
| 100-149   |           1 |
| 150-199   |           1 |
+-----------+-------------+


SQL:

SET @username = 'dad';
(
	SELECT
		  username
		, score
	FROM 
		  game_result 
	WHERE 
		  score < ( SELECT score FROM game_result WHERE username = @username )
	ORDER BY score DESC
	LIMIT 2
) UNION (
	SELECT
		  username
		, score
	FROM 
		  game_result 
	WHERE 
		  score >= ( SELECT score FROM game_result WHERE username = @username ) 
	ORDER BY score ASC
	LIMIT 3
)


Result:

+----------+-------+
| username | score |
+----------+-------+
| gdfgfd   |    71 |
| weqw     |    46 |
| dad      |    82 |
| fdsfs    |    93 |
| cxzcxz   |   120 |
+----------+-------+