Skip to content
Advertisement

calculate percentage/repartition of values with a sql query

I have the following table

type color value
A white true
B black false
c yellow true
d red true
f green false

and I want to calculate with a sql query the percentage of rows having value equal to true , here for example we have 3 trues over a total of 5 lines which makes a percentage of 60% of types having a value equal to true , any idea how to fix this please ?

Advertisement

Answer

Do you just want a single value to be returned?

Depending on which RDBMS you’re using boolean values are handled differently, but the basic structure should be similar to…

SELECT
  SUM(CASE WHEN value = true THEN 1 ELSE 0 END) * 1.0 / COUNT(*)
FROM
  yourTable
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement