简体   繁体   中英

Is there a way to find percentage of non-zero vs zero values in one column?

I'm supposed to find the percentage of people having received aid.

I'm assuming the best way to do this is find the number rows who received 0 aid, and the number of rows that have a greater than 0 value, create two variables for those and divide accordingly to find the percentage. It's been a while since I've worked with sql so this is challenging me.

select
    rprawrd_aidy_code as year,
    sum(rprawrd_accept_amt)

from
    rprawrd

where
    rprawrd_aidy_code = '1819'

group by
    rprawrd_aidy_code

This only gives me a total of the amount of aid provided for the year in question. I need to figure out the total rows that received vs the total that didnt.

If the only output you need from your script is that ratio, there are a few ways to go about this one:

WITH cte (awrd) AS(
    SELECT
        CASE WHEN rprawrd_accept_amt > 0 THEN 1.0
        ELSE 0.0
        END awrd
    FROM rprawrd
    WHERE rprawrd_ady_code = '1819'
    )
SELECT SUM(awrd)/COUNT(awrd)
FROM cte

This will get you the percentage of people who received an award, but if you need to know the amounts as well you'll have to approach it differently.

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