0

I need some help with counting both unique and duplicate values in MySQL. I want to know how many records there are total, and also how many is there two times and three times and so on...

Do I need to use UNION or something? I think SUM would be the best solution for me because of I might use some joins with this in future.

Sample data:

| custId | name   |
|--------|--------|
| 1001   | Alex   |
| 1001   | Alex   |
| 1002   | Daniel |
| 1003   | Mark   |
| 1002   | Daniel |

Sample results:

| total | twoTimes | threeTimes |
|-------|----------|------------|
|     3 |        2 |          0 |

Thanks in advance.

lingo
  • 1,848
  • 6
  • 28
  • 56

2 Answers2

0

Just a basic group by should do it

    SELECT YourValue, Count(YourValue)
    FROM YourTable
    GROUP BY YourValue

If you want only a category, like unique values ADD

   HAVING Count(YourValue)  = 1
Juan Carlos Oropeza
  • 47,252
  • 12
  • 78
  • 118
0

Here is my approach:

http://sqlfiddle.com/#!9/9411dc/3

SELECT c.cnt AS `times`, COUNT(c.name) cnt
FROM (SELECT name, COUNT(custId) cnt
FROM cust
GROUP BY name) c
GROUP BY c.cnt;

that is not exactly what you did ask (you asked for pivot table which is very difficult to realize). So if you want to make it pivot you can read here: MySQL pivot table

And if you are sure that you have very small max of duplicate count your pivot query could be:

http://sqlfiddle.com/#!9/9411dc/5

SELECT 
  SUM(IF(c.cnt=1,1,0)) AS `Unique`, 
  SUM(IF(c.cnt=2,1,0)) AS `Two times`, 
  SUM(IF(c.cnt=3,1,0)) AS `Three times`, 
  SUM(IF(c.cnt=4,1,0)) AS `Four times`
FROM (SELECT name, COUNT(custId) cnt
FROM cust
GROUP BY name) c
Community
  • 1
  • 1
Alex
  • 16,739
  • 1
  • 28
  • 51