我的当前表格如下
public.transactions
storeId FeatureA FeatureB FeatureC Details
123 true false false ... (JSON)
123 false false false
123 true false true
基本上,交易表会跟踪触发交易的特定功能。我需要获取特定ID的每个功能的数量,例如:
storeId FeatureA FeatureB FeatureC
123 2 0 1
我已经进行了3次独立计数
Select *
FROM public.transactions
where "storeId" = 123 AND "FeatureA" = true
但是似乎效率很低。
答案 0 :(得分:4)
您是否只需要条件聚合? Postgres通过支持filter
子句使此操作变得容易:
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;
答案 1 :(得分:3)
有条件聚合:
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