简体   繁体   中英

Grouping a percentage calculation in postgres/redshift

I keep running in to the same problem over and over again, hoping someone can help...

I have a large table with a category column that has 28 entries for donkey breed, then I'm counting two specific values grouped by each of those categories in subqueries like this:

WITH totaldonkeys AS (
    SELECT donkeybreed,
           COUNT(*) AS total
    FROM donkeytable1
    GROUP BY donkeybreed
)
,
sickdonkeys AS (
    SELECT donkeybreed,
           COUNT(*) AS totalsick
    FROM donkeytable1
    JOIN donkeyhealth on donkeytable1.donkeyid = donkeyhealth.donkeyid
    WHERE donkeyhealth.sick IS TRUE
    GROUP BY donkeybreed
)
,

It's my goal to end up with a table that has primarily the percentage of sick donkeys for each breed but I always end up struggling like hell with the problem of not being able to group by without using an aggregate function which I cannot do here:

SELECT (CAST(sickdonkeys.totalsick AS float) / totaldonkeys.total) * 100 AS percentsick,
                totaldonkeys.donkeybreed
    FROM totaldonkeys, sickdonkeys
    GROUP BY totaldonkeys.donkeybreed

When I run this I end up with 28 results for each breed of donkey, one correct I believe but obviously hundreds of useless datapoints.

I know I'm probably being really dumb here but I keep hitting in to this same problem again and again with new donkeydata, I should obviously be structuring the whole thing a new way because you just can't do this final query without an aggregate function, I think I must be missing something significant.

You can easily count the proportion that are sick in the donkeyhealth table

SELECT d.donkeybreed,
       AVG( (dh.sick)::int ) AS proportion_sick
FROM donkeytable1 d JOIN
     donkeyhealth  dh
     ON d.donkeyid = dh.donkeyid
GROUP BY d.donkeybreed

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