简体   繁体   中英

Get percentage of each unique value in column (mySQL)

I'm trying to come up with a query that will find all the unique values in a particular column and then count the number of instances of each unique value and give back that count and the percentage for each unique value versus the total number of values.

Here's what I have, but it's not working as it only gives me the first unique item, not all the possible options.

select 
`column1`
, ROUND( 
        (count(`column1`)* 100 / (select count(*) from full_db3 
where `exuid` in ('e7dfb4dd-0cd2-44df-bd35-6ecc9a061756','56baea00-253b-428e-88fc-9969688ea9c8'))
      ), 2)
  as Percentage
from full_db3 where `exuid` in ('e7dfb4dd-0cd2-44df-bd35-6ecc9a061756','56baea00-253b-428e-88fc-9969688ea9c8')

What this gives me now is the first unique value in column1 and Percentage as 100%.

I'm going to be passing in exuid values dynamically, so it'll always be a different number, so either I have to count the number of values I'm passing into this before I pass it or the query has to count them somewhere. Not quite sure how to do either.

you need to group by the column you want the count for. Then divide that number by the total number of rows in the table using a subquery:

select columnA, count(*), (COUNT(*) / (SELECT COUNT(*) FROM myTable)) * 100 FROM myTable group by columnA;

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