简体   繁体   中英

MySQL count records matching distinct column values

My database includes a column for people's names. Unfortunately, the column includes slight variations of people's name. I would like a query that returns a distinct list of names and the count of records for each variation.

Here is what the column looks like:

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

I want this result:

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

This is my query:

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

But it only returns:

Stan c Smith  6

I have two questions:

  1. Why does MySQL only list one result?
  2. What do I need to do to get the results I am looking for?

Thank you.

You should use group by, the below query should give you the result

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

To answer your questions:

1) Count is an aggregate function, which returns the total number of rows, by default this will return 1 value unless you use a GROUP BY

2) Use GROUP BY Customer this will group all Customers with the same name together, then running a count should result in a count of each unique instance:

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

See the SQLFiddle for a demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM