如何计算MySQL中列值的出现次数?

时间:2014-03-29 13:37:13

标签: mysql sql

我的查询:

SELECT 
 max(if(`field_name`='your-name', `field_value`, null )) AS 'Name',
 max(if(`field_name`='your-email', `field_value`, null )) AS 'email',
 max(if(`field_name`='your-subject', `field_value`, null )) AS 'subject'


FROM Complaints 
WHERE `form_name` = 'Complaint'  
GROUP BY `submit_time`;

,表格看起来像那样

+---------+---------------+---------+
|  Name   |     email     | Subject |
+---------+---------------+---------+
| Mike AA | test@test.com | test    |
| John    | a@test.com    | w       |
| Mike AA | test@test.com | zzzz    |
+---------+---------------+---------+

我正在尝试为值名称相同的count添加新列 所以就是这样。 组记录“名称相同”

+---------+---------------+---------+---------------------+
|  Name   |     email     | Subject | Number of Complaint |
+---------+---------------+---------+---------------------+
| Mike AA | test@test.com | test    |                   2 |
| John    | a@test.com    | w       |                   1 |
+---------+---------------+---------+---------------------+

非常感谢你的帮助

1 个答案:

答案 0 :(得分:2)

这是你在找什么?

SELECT name, email, min(Subject) as Subject, count(*) as NumComplaint
FROM `contactus`  c
WHERE `form_name` = 'Complaint'  
GROUP BY name, email;