简体   繁体   English

使用“ MYSQL分组”对总记录进行计数

[英]Count Total Records with Group By Column MYSQL

I have a table of results for some trail races, this has all the runner for each race in a single table, I can filter off a single runner and see their race results but I want to count the total runners in a race to show the finishing position, this query gets me nearly there but its counting ALL the records in the table 我有一些越野比赛的结果表,该表将每场比赛的所有跑步者都放在一个表格中,我可以过滤出单个跑步者并查看他们的比赛结果,但我想计算一场比赛中的总跑步者人数,以显示结束位置,此查询使我快到那里了,但它对表中的所有记录进行计数

SELECT (select count(ID) 
        FROM `results` 
        where Race = results.race) as TotalRunners, fullname, place 
from results 
where fullname = 'Michael Todd'

So I need the Race = results.race to be the grouped by fields 所以我需要将Race = results.race按字段分组

this is the current output 这是当前的输出

TotalRunners
fullname
place
4815
Michael Todd
3
4815
Michael Todd
2
4815
Michael Todd
6
4815
Michael Todd
5
4815
Michael Todd
10
4815
Michael Todd
12
4815
Michael Todd
2
4815
Michael Todd
4
4815
Michael Todd
5
4815
Michael Todd
15
4815
Michael Todd
5
4815
Michael Todd
23
4815
Michael Todd
3

The 4815 value should be the total runners in each of the races. 4815的值应该是每场比赛的总跑步人数。

Assuming this: 假设这样:

fullname      | place | race
=============================
michael todd  |   4   |  1
michael todd  |   3   |  2
michael todd  |   9   |  3
bob sanchez   |   2   |  1
bob sanchez   |   1   |  2
bob sanchez   |   5   |  3




SELECT *, 
(
   SELECT count(*) FROM runners WHERE runners.race = r.race
) AS total_runners 
FROM runners r 
WHERE 
    fullname = "Michael Todd" 
GROUP BY 
race 

Should return the correct count of runners when querying by one person. 一人查询时,应返回正确的跑步人数。

CREATE TABLE `runners` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`race` int(11) DEFAULT NULL,
`fullname` varchar(50) DEFAULT NULL,
`position` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;



INSERT INTO `runners` (`id`, `race`, `fullname`, `position`)
VALUES
    (1, 1, 'Michael Todd', 1),
    (2, 2, 'Michael Todd', 5),
    (3, 3, 'Michael Todd', 8),
    (4, 1, 'Miguel Sanchez', 2),
    (5, 2, 'Miguel Sanchez', 4),
    (6, 3, 'Miguel Sanchez', 13),
    (7, 1, 'Bob Villa', 22),
    (8, 3, 'Bob Villa', 3);

SQL Fiddle: SQL提琴:

http://sqlfiddle.com/#!9/5af3dc/1 http://sqlfiddle.com/#!9/5af3dc/1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM