简体   繁体   中英

get distinct value count in mysql select query

I have one table in MySQL as below.

id | number | name | type

111 | 123 | XYZ | bar

222 | 234 | ABC | restaurants

111 | 007 | PKA | food

111 | 123 | XYZ | bar

333 | 123 | XYZ | bar

Now what I would like to get is total size of number which is having unique id. Meaning in my case 111 and 333 have same number that is 123 . So the total count for number 123 is 2. Here I don't want to count 111 again as you can see that 111 came twice for the number 123 but I don't want to add it in the total size as its already there in the count. So i want the unique id's count which is having same number.

OUTPUT i want from the query is :-

123 (XYZ) - 2 (There are total 3 entry but 111 id is repeated for number 123 and I don't want duplicated one. So I want to take both id and number in consideration while getting the count.)

234 (ABC) - 1

007 (PKA) - 1

I used the Group By for finding duplicate values but didn't get the proper output as per my requirements. Any help or suggestions would be welcomed.

select number, count(distinct id)
from your_table
group by number

also possible:

select id, number, name, type, 
       count(distinct id) over (partition by number) numOfDistictIds
from table
order by number

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