Skip to content
Advertisement

SQL / Postgresql count multiple columns with conditions

I have a simple table of the form:

id gender a_feature (bool) b_feature (bool) xyz_feature (bool)

and I want to sum over all feature columns dependent on gender.

metric male female
a_feature 345 3423
b_feature 65 143
xyz_feature 133 5536

Is there a simple way to do this, e.g. using the information_schema.

I found only the solution below, but this is very ugly:

Advertisement

Answer

You can unpivot and aggregate. One method is:

In Postgres, you would unpivot using a lateral join:

You can generate the list for values() using information_schema.columns if you are reluctant to type it all in.

EDIT:

You can construct the values clause using something like this:

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement