2

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.

2 Answers 2

5

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;
Sign up to request clarification or add additional context in comments.

Comments

3

With conditional aggregation:

select storeid,
  sum(case when featurea then 1 else 0 end) featurea,
  sum(case when featureb then 1 else 0 end) featureb,
  sum(case when featurec then 1 else 0 end) featurec
from tablename
group by storeid

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.