Shevtsov Eugene Asked:2021-12-19 22:20:48 +0000 UTC2021-12-19 22:20:48 +0000 UTC 2021-12-19 22:20:48 +0000 UTC 如何获得具有分组和公共记录数量的选择 772 这里有张桌子: +-----+-------+ | id | team | +-----+-------+ | 1 | 1 | | 2 | 2 | | 3 | 2 | | 4 | 3 | +-----+-------+ 我需要从这个表中获取所有用户并计算他们团队中总共有多少用户。 SELECT id, count(team), team FROM user_team GROUP BY id 正如预期的那样,它返回一个用户有一个命令。 mysql 3 个回答 Voted splash58 2021-12-19T22:33:56Z2021-12-19T22:33:56Z 您需要按团队分组,然后按团队编号将子查询与主查询组合 select id, cnt from user_team join (SELECT team, count(id) cnt FROM user_team GROUP BY team ) t using(team) 演示 Best Answer Akina 2021-12-20T00:14:13Z2021-12-20T00:14:13Z SELECT *, COUNT(*) OVER (PARTITION BY team) users_in_team FROM user_team; 小提琴 Shevtsov Eugene 2021-12-19T22:34:28Z2021-12-19T22:34:28Z 我不知道我做得对不对,但我没有想出比这更聪明的东西: SELECT id, team, COUNT(DISTINCT ut2.user) FROM user_team ut LEFT JOIN user_team ut2 ON ut.team = ut2.team GROUP BY id
您需要按团队分组,然后按团队编号将子查询与主查询组合
演示
小提琴
我不知道我做得对不对,但我没有想出比这更聪明的东西: