MySQL count unique and duplicate values

只愿长相守 提交于 2020-01-17 05:29:14

问题


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.


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/37301344/mysql-count-unique-and-duplicate-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!