MySQL计数记录匹配不同的列值

时间:2016-05-10 04:42:02

标签: mysql

我的数据库包含一个人名列。不幸的是,该专栏包含了人们名字的轻微变化。我想要一个查询,返回一个不同的名称列表和每个变体的记录数。

以下是该列的内容:

+---------------+
| Customer      |
+---------------+
| Stan c. Smith |
| Stan c Smith  |
| Stan c. Smith |
| Stan c Smith  |
| Stan c, Smith |
| Stan c Smith  |
+---------------+

我想要这个结果:

Stan c. Smith 2
Stan c Smith  3
Stan c, Smith 1

这是我的疑问:

SELECT 
    DISTINCT(`Customer`) as aCustomer, COUNT(`Customer`)
FROM
    `customerTable`
where 
    `Customer` like "%Stan%c%Smith%"

但它只会返回:

Stan c Smith  6

我有两个问题:

  1. 为什么MySQL只列出一个结果?
  2. 我需要做些什么来获得我想要的结果?
  3. 谢谢。

2 个答案:

答案 0 :(得分:0)

你应该使用group by,下面的查询应该给你结果

SELECT 
     `Customer` as aCustomer, COUNT(`Customer`) as count
FROM
      `customerTable`
where 
    `Customer` like "%Stan%c%Smith%"
group by aCustomer

答案 1 :(得分:0)

回答你的问题:

1)Count是一个聚合函数,它返回总行数,默认情况下这将返回1个值,除非你使用GROUP BY

2)使用GROUP BY Customer这将所有具有相同名称的客户组合在一起,然后运行计数将导致每个唯一实例的计数:

SELECT 
    `Customer`, COUNT(`Customer`)
FROM
    `customerTable`
WHERE
    `Customer` like "%Stan%c%Smith%"
GROUP BY `Customer`

请参阅SQLFiddle了解演示