Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

count on multiple boolean columns

Tags:

sql

postgresql

My Current Table looks as follows

public.transactions

storeId     FeatureA  FeatureB  FeatureC  Details
123         true      false     false     ... (JSON)
123         false     false     false
123         true      false     true

basically the transaction table tracks the specific feature that triggered the transaction. I need to grab the count for each feature for a specific id, something like this:

storeId     FeatureA  FeatureB  FeatureC
123         2         0         1     

I've been getting the count doing 3 individual counts

Select *
FROM public.transactions
where "storeId" = 123 AND "FeatureA" = true

but the seems really inefficient.

like image 874
Saad Avatar asked May 11 '26 22:05

Saad


1 Answers

Do you just want conditional aggregation? Postgres makes this easy by supporting the filter clause:

select storeid,
       count(*) filter (where featureA) as num_featureA,
       count(*) filter (where featureB) as num_featureB,
       count(*) filter (where featureC) as num_featureC
from public.transactions t
group by storeid;
like image 67
Gordon Linoff Avatar answered May 13 '26 14:05

Gordon Linoff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!