Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compute ratio of group sizes using SQL

Tags:

sql

vertica

Consider a simple group by query:

select foo, count(*)
    from mytable where bar=10 
group by foo

This returns a table that has the following form:

foo | count
----+------
a   | 100
b   | 200
c   | 300

My goal is to get, using a single query the following table:

foo | count | ratio
----+-------+-------
a   | 200   | 18.2
b   | 300   | 27.3
c   | 600   | 54.5

In practice, I have more possible values of foo thus answers like those in here are not helpful. Furthermore, not that the ratio is rounded and multiplied by 100.

What is the best practice to do this?

like image 306
Dror Avatar asked Aug 23 '16 06:08

Dror


People also ask

How do you calculate proportions in SQL?

Finding Percentages between two columns is straightforward. You can simply use the column names and the division operator “/” to divide values in one column by another. The result is a list of values that correspond to the result of the division of all the values in the two columns.

How do I count the number of rows per group in SQL?

To count the number of rows, use the id column which stores unique values (in our example we use COUNT(id) ). Next, use the GROUP BY clause to group records according to columns (the GROUP BY category above). After using GROUP BY to filter records with aggregate functions like COUNT, use the HAVING clause.

How do you calculate percent discount in SQL query?

The formula will need to be something like: col1 * 0. col2 (both columns 1&2 can be null). Col1 is the GrossAmount(decimal(10,2) and Col2(smallint) is the percent discount.


1 Answers

Sounds like you want something like this:

select foo, count(*),
       count(*) * 100.0 / sum(count(*)) over () as ratio
from mytable
where bar = 10 
group by foo;

This does not guarantee that the value adds up to exactly 100% when rounded. That is a much tricker problem, usually better handled at the application layer. This does produce the "correct" answer, using floating point numbers.

like image 192
Gordon Linoff Avatar answered Oct 30 '22 12:10

Gordon Linoff