MySQL:累积字段中每个特定值的出现次数

时间:2014-05-12 08:43:09

标签: mysql sql sum accumulate

我想获得一个字段,其中包含字段中值的出现次数。

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,但我不确定如何。

1 个答案:

答案 0 :(得分: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