2017-04-04 85 views
0

我有一些追蹤賽的結果表,這裏有一張表在每張表中的所有參賽者,我可以過濾掉一個參賽者並看到他們的比賽結果,但我想要要計算總選手在比賽中表現出結束位置,這個查詢獲取我幾乎存在,但其在表計數的所有記錄按列分組記錄總記錄數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值應該是每場比賽的總跑者。

回答

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