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

Calculate percentage of false records to total records within a aggregate function

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

Problem

I'm looking for a solution to calculate a percentage rate of a boolean value:

Model:

Products 1 n Components

Components.essential is a boolean attribute

What I want to calculate is something like:

SELECT products.*, count(comp_a.essential)/count(comp_b.essential) AS essential_percentage
From products
INNER JOIN components AS comp_a ON products.id = comp_a.product_id
INNER JOIN components AS comp_b ON products.id = comp_b.product_id
WHERE comp_a.essential = 1
GROUP BY products.id


Unfortunately this statement calculates way too many components as there are two INNER JOIN on the components model...

Any help on this?

Markus

Solution

Note the standard GROUP BY clause.

This gives "true" percent because I assume that's what you mean (not false)

SELECT
  p.*, 
  count(CASE WHEN c.essential = 1 THEN 1 END) / count(*) AS essential_percentage
From 
  products p
  LEFT OUTER JOIN 
  components c ON p.id = c.product_id
GROUP BY 
  p.*;


or

count(nullif(c.essential, 0)) / count(*) AS essential_percentage

Code Snippets

SELECT
  p.*, 
  count(CASE WHEN c.essential = 1 THEN 1 END) / count(*) AS essential_percentage
From 
  products p
  LEFT OUTER JOIN 
  components c ON p.id = c.product_id
GROUP BY 
  p.*;
count(nullif(c.essential, 0)) / count(*) AS essential_percentage

Context

StackExchange Database Administrators Q#10453, answer score: 3

Revisions (0)

No revisions yet.