不确定如何最好地给问题加上标题。
我有一张桌子,记录着玩家的胜利。我需要查询多少个球员有多少个胜利。
以下是示例数据库: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'并选择计数),但是如何将这些结果分组到预期结果中?
谢谢!
答案 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 |
答案 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