2014-05-12 134 views
1

我想获取包含字段中值的出现次数的字段。MySQL:累积字段中每个特定值的出现次数

CREATE TABLE `events` (
`id` INT NOT NULL AUTO_INCREMENT, 
`country` VARCHAR(2) NOT NULL, 
PRIMARY KEY (`id`)); 

INSERT INTO `events` (`country`) VALUES 
('es'), ('fr'), ('uk'), 
('uk'), ('es'), ('uk'), 
('fr'), ('it'), ('es'), 
('es'), ('it'), ('uk'), 
('fr'), ('es'), ('de') 

也就是说,给出this SQLFiddle,我想现场accumulated添加到结果,包含数量,在现场country价值已经出现,直到该行倍。

SELECT e.*, 
(SELECT COUNT(*) FROM `events` AS e2 
WHERE e2.country = e.country) AS times 
FROM `events` AS e 

ID | COUNTRY | TIMES | ACCUMULATED 
----+---------+-------+------------ 
1 | es  | 5  | 1 
2 | fr  | 3  | 1 
3 | uk  | 4  | 1 
4 | uk  | 4  | 2 
5 | es  | 5  | 2 
6 | uk  | 4  | 3 
7 | fr  | 3  | 2 
8 | it  | 2  | 1 
9 | es  | 5  | 3 
10 | es  | 5  | 4 
11 | it  | 2  | 2 
12 | uk  | 4  | 4 
13 | fr  | 3  | 3 
14 | es  | 5  | 5 
15 | de  | 1  | 1 

我想这是某种条件SUM,但我不知道如何。

+0

你通常不会储存这种事情,因为它可以“在即时”很容易计算。 http://sqlfiddle.com/#!2/1f6bb2/62 – Strawberry

+0

@Strawberry也许我使用'add'来困惑你;我显然不是指将该字段添加到表中,而是添加到结果集中。 – Jago

回答

2

没有必要。我认为你只需要第二个条件“直到该行”:

select e.*, 
     (select count(*) from `events` as e2 
     where e2.country = e.country 
     ) as times, 
     (select count(*) from `events` as e3 
     where e3.country = e.country AND e3.id <= e.id 
     ) as accumulated 
from `events` as e 

http://sqlfiddle.com/#!2/1f6bb2/44

+0

这个解决方案在较大的数据集上会很慢:-( – Strawberry

+0

是的,这是真的。如果响应时间低于可接受的限度,您应该考虑在表中存储“时间”和“累积”并在插入时计算它。 – semao

+0

.. 。或只是切换到我上面建议的方法之一;-) – Strawberry