Search code examples
mysqlsqlsubtotal

Amount of occurrences of a value in a field, for each row


I want to be able to retrieve, for each row, the number of total appearances of one value of one field.

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')

That is, given this SQLFiddle, I want to able to add a field to the results, that conditionally adds the number of appearances of each value of field country.

SELECT * from `events`;

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

If possible, it would be great that partial results (LIMIT x, y) would still return total sums for each field:

SELECT * from `events` LIMIT 3, 7;

ID  | COUNTRY | TIMES
----+---------+------
4   | uk      | 4
5   | es      | 5
6   | uk      | 4
7   | fr      | 3
8   | it      | 2
9   | es      | 5
10  | es      | 5

As per this SQLFiddle.


Solution

  • Is this what you want?

    select e.*,
           (select count(*) from events e2 where e2.country = e.country
           ) as times
    from `events` e;
    

    It seems to meet your needs. If you want to actually change the table:

    alter table events add times unsigned;
    
    update events e
        set times = (select count(*) from events e2 where e2.country = e.country);