MySQL-按分组结果分组

时间:2018-10-30 20:30:42

标签: mysql group-by

不确定如何最好地给问题加上标题。

我有一张桌子,记录着玩家的胜利。我需要查询多少个球员有多少个胜利。

以下是示例数据库:https://www.db-fiddle.com/f/gCEKmtPQr7nvhiZDyexn9C/0 这是预期的结果:

<?php

// make sure that this folder is NOT accesible as an URL
putenv("GNUPGHOME=/var/www/.gnupg/");

error_reporting(E_ALL);
$res = gnupg_init();
gnupg_seterrormode($res,GNUPG_ERROR_WARNING);

$info = gnupg_keyinfo($res, '');
echo "Key - Info<pre>";
var_dump($info);
echo "</pre>";

我有点迷茫。我可以轻松获得每位玩家的获胜次数(按user_id分组,其中status ='win'并选择计数),但是如何将这些结果分组到预期结果中?

谢谢!

2 个答案:

答案 0 :(得分:1)

  • 您将需要对Group By使用两级Select查询。子选择查询也称为Derived Table
  • 在内部选择查询中,获得每位用户的总赢额。
  • 现在,在外部选择中,对获胜总数进行Group By,并为他们计算用户数。

请尝试以下操作:

SELECT 
  dt.total_wins AS wins, 
  COUNT(*) AS players_count 
FROM 
(
  SELECT
    user_id, 
    COUNT(*) AS total_wins 
  FROM a 
  WHERE status = 'win' 
  GROUP BY user_id
) AS dt 
GROUP BY dt.total_wins 

模式(MySQL v5.7)

CREATE TABLE a (status VARCHAR(255), user_id int);

INSERT INTO a (status, user_id)
VALUES ('win', 1),
('win', 2),
('win', 3),
('win', 2),
('win', 4),
('win', 4),
('win', 1),
('not win', 1);

查询结果

| wins | players_count |
| ---- | ------------- |
| 1    | 1             |
| 2    | 3             |

View on DB Fiddle

答案 1 :(得分:1)

下面是一个没有CASE语句的示例:

获得wins_per_user后,只需计算user_ids,然后再次按wincount分组:

SELECT
  wincount AS WinCount, count(user_id) as UserCount
FROM
  (SELECT 
   count(*) as wincount, user_id
  FROM a 
    where status='win'
  GROUP BY user_id) as wins_per_user
GROUP BY wincount

结果

WinCount UserCount
1        1
2        3
相关问题