简体   繁体   中英

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

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.

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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