简体   繁体   中英

SQL Query and Count

I have this SQL query so far that finds the percentage based on all kinds of "sex"

select (
         (select count(*) from hw where DISCHARGE_STATUS = 'B') 
         / 
         count(*) 
         * 100 
       ) as Percentage 
from hw

Lets say my table is

SEX     DISCHARGE STATUS
1             A
1             B
2             B
2             B
2             B

The percentage of Discharge B would be 80%/100% TOTAL COUNT : ALL SEX

Now lets say I need to find the percentage the same way but categorize it with SEX types 1 and 2 1 would be 20/100% TOTAL COUNT : FOR SEX TYPE 1 and DISCHARGE TYPE B 2 would be 60/100% TOTAL COUNT : FOR SEX TYPE 2 and DISCHARGE TYPE B

I tried adding a GROUP BY SEX to the end of the query but that did not help, what can I do?

Thanks in advance :)

Instead of querying hw twice you can do this in one pass and get the sub counts by using SUM:

select 
  count(*) as count_total,
  sum(discharge_status = 'B') as count_b,
  sum(sex = 1) as count_sex1,
  sum(discharge_status = 'B' AND sex = 1) as count_b_sex1
from hw;

(An expression that results in TRUE is 1, one that results in FALSE is 0 in MySQL. Thus you SUM 1 per matching record. In other words: you count.)

Then do whatever math you want on it:

select 
  sum(discharge_status = 'B' AND sex = 1) / 
  sum(discharge_status = 'B') * 100 as percent_sex1_in_b
from hw;

(In this simple example where you only use status B counts, you can move discharge_status = 'B' to a WHERE clause of course.)

If you want the percent of each combination of SEX and DISCHARGE_STATUS then this query would work.

SELECT SEX, DISCHARGE_STATUS,
       COUNT(*) / (SELECT COUNT(*) FROM hw WHERE SEX = hw.SEX AND DISCHARGE_STATUS = hw.DISCHARGE_STATUS) pct

FROM   hw

GROUP BY SEX, DISCHARGE_STATUS

SQLFiddle

You can try this for sex type 1

((select sum(sex) from hw where sex=1)/(select sum(sex) from hw))

*

((select count(DISCHARGE_STATUS) from hw where (DISCHARGE_STATUS)=B)/select count(*) from hw))

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