Search code examples
sqloracleoracle11g

Need to do a group by count of id and at the same time get the total of count without a group by


Need to do a group by count of id and at the same time get the total of count without a group by This is so I can get the total count of the id and check the percentage of each group by category compared to the total count.

-- Its for an oracle sql script

Something like the following is what I currently have:

SELECT
    count(id) as unit_count,
    category
FROM sales
GROUP BY category
ORDER BY count(id) DESC;

SELECT
    count(id) as total_count
FROM sales

I am not sure how to combine the above two

The final result I am looking for is the following:

category count percentage_of_total
televisions 100 25%
mobile phones 300 75%

Solution

  • Window functions are calculated after aggregates. This means that SUM(COUNT(*)) OVER () will total up the counts across the entire result set...

    SELECT
        category,
        count(id) as unit_count,
        COUNT(*) / SUM(COUNT(*)) OVER () AS percentage_of_all_units
    FROM sales
    GROUP BY category
    ORDER BY count(id) DESC;