每行中字段中值的出现次数

时间:2014-05-12 05:27:19

标签: mysql sql subtotal

我希望能够为每一行检索一个字段值的总外观数。

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,我希望能够在结果中添加字段,有条件地会添加字段{{1}的每个值的出现次数}}

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 )仍会返回每个字段的总和会很好:

LIMIT x, y

根据this SQLFiddle

1 个答案:

答案 0 :(得分:0)

这是你想要的吗?

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

它似乎满足您的需求。如果你想真正改变表格:

alter table events add times unsigned;

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