MySQL - 计算多列中的出现次数?

时间:2016-06-20 14:55:01

标签: mysql

我想根据帖子计算每个人的出现次数,无论日期如何。

数据是这样的:

date       | post1    | post2    | post3
--------------------------------------------
01/01/2016 | Anna     | Bella    | Charlie
03/01/2016 | Bella    | Charlie  | Dan
05/01/2016 | Dan      | Charlie  | Evan
06/01/2016 | Charlie  | Anna     | Evan

预期结果是:

name     | post1    | post2    | post3
-------------------------------------------
Anna     | 1        | 1        | 0
Bella    | 1        | 1        | 0
Charlie  | 1        | 2        | 1
Dan      | 1        | 0        | 1
Evan     | 0        | 0        | 2

目前,我可以使用GROUP BY输出每个帖子的计数结果,如下所示:

SELECT post1 as name, COUNT(post1) as count FROM data GROUP BY name
(data from post1)
name     | count
-------------------
Anna     | 1       
Bella    | 1       
Charlie  | 1       
Dan      | 1       

SELECT post2 as name, COUNT(post1) as count FROM data GROUP BY name
(data from post2)
name     | count
-------------------
Anna     | 1       
Bella    | 1       
Charlie  | 2       

但是我希望像预期结果一样输出它,同时计算所有帖子。这可能只使用查询,还是需要创建存储过程?

1 个答案:

答案 0 :(得分:0)

正确的做法是:

DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(date DATE NOT NULL
,user VARCHAR(20) NOT NULL
,post_no INT NOT NULL
,PRIMARY KEY(date,post_no)
);

INSERT INTO my_table VALUES
('2016-01-01','Anna',1),
('2016-01-03','Bella',1),
('2016-01-05','Dan',1),
('2016-01-06','Charlie',1),
('2016-01-01','Bella',2),
('2016-01-03','Charlie',2),
('2016-01-05','Charlie',2),
('2016-01-06','Anna',2),
('2016-01-01','Charlie',3),
('2016-01-03','Dan',3),
('2016-01-05','Evan',3),
('2016-01-06','Evan',3);

SELECT user,post_no,COUNT(*) total FROM my_table GROUP BY user,post_no;
+---------+---------+----------+
| user    | post_no | total    |
+---------+---------+----------+
| Anna    |       1 |        1 |
| Anna    |       2 |        1 |
| Bella   |       1 |        1 |
| Bella   |       2 |        1 |
| Charlie |       1 |        1 |
| Charlie |       2 |        2 |
| Charlie |       3 |        1 |
| Dan     |       1 |        1 |
| Dan     |       3 |        1 |
| Evan    |       3 |        2 |
+---------+---------+----------+

此问题的任何其他方面最好在应用程序级代码中解决。