HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlModerate

Need separate columns that calculate percentage

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
columnsneedseparatethatcalculatepercentage

Problem

I have the following table:

NAME
Alex
Bob 
Bob
Tim
Alex
Roger


I need to produce the following:

Name    Count Percentage
 Alex    2     33%
 Bob     2     33%
 Roger   1     16.6%
 Tim     1     16.6%


I have no idea where to start. I can do the initial query for the count which is simple.

Solution

Possible with a single SELECT:

SELECT name, count(*), to_char((count(*) * 100.0
                          / sum(count(*)) OVER ()), 'FM990.00" %"') AS percent
FROM   t
GROUP  BY 1
ORDER  BY 1;


count(*) is a separate form of the function and slightly faster than count(). Assuming all columns to be NOT NULL, else you may have to use the latter.

You can run the window aggregate function sum(count(*)) OVER () to get the total in the same SELECT. Consider the sequence of event in a SELECT:

  • How will the order of operations in this query affect my results?



This uses one sequential scan instead of two and is typically twice as fast as using a subquery for the total count.

to_char() prettifies the output:

name  count  percent
-----------------------
Alex  2      33.33 %
Bob   2      33.33 %
Roger 1      16.67 %
Tim   1      16.67 %

Code Snippets

SELECT name, count(*), to_char((count(*) * 100.0
                          / sum(count(*)) OVER ()), 'FM990.00" %"') AS percent
FROM   t
GROUP  BY 1
ORDER  BY 1;
name  count  percent
-----------------------
Alex  2      33.33 %
Bob   2      33.33 %
Roger 1      16.67 %
Tim   1      16.67 %

Context

StackExchange Database Administrators Q#75345, answer score: 10

Revisions (0)

No revisions yet.