按列MYSQL计算总记录数

时间:2017-04-04 14:59:23

标签: mysql

我有一些赛道比赛的结果表,这个赛道上每场比赛都有赛跑者,我可以过滤掉一个赛跑者,看看他们的比赛结果,但我想计算比赛中的总赛跑者数为了显示完成位置,这个查询几乎让我在那里,但它计算表中的所有记录

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

所以我需要Race = results.race按字段分组

这是当前的输出

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

4815值应该是每场比赛的总跑步者。

1 个答案:

答案 0 :(得分:0)

假设:

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 

当一个人查询时,应该返回正确的跑步者数量。

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小提琴:

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