依赖多个布尔列

Saa*_*aad 2 sql postgresql

我当前的表如下所示

public.transactions

storeId     FeatureA  FeatureB  FeatureC  Details
123         true      false     false     ... (JSON)
123         false     false     false
123         true      false     true
Run Code Online (Sandbox Code Playgroud)

基本上,交易表跟踪触发交易的特定功能。我需要获取特定 id 的每个功能的计数,如下所示:

storeId     FeatureA  FeatureB  FeatureC
123         2         0         1     
Run Code Online (Sandbox Code Playgroud)

我一直在进行 3 次单独计数

public.transactions

storeId     FeatureA  FeatureB  FeatureC  Details
123         true      false     false     ... (JSON)
123         false     false     false
123         true      false     true
Run Code Online (Sandbox Code Playgroud)

但这似乎效率很低。

Gor*_*off 5

您只想要条件聚合吗?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;
Run Code Online (Sandbox Code Playgroud)