首页 > 解决方案 > postgresql 获取多个值的唯一计数

问题描述

我是 POSTGRESQL 的新手,正在尝试获取deleted_by is null多个comp_source_store值的唯一计数:[“petsmart”、“amazon”、“qfc”]

我可以通过一个查询得到我的号码,如下所示:

select 
    count(distinct(comp_upc)) as petsmart from matches where 
    comp_source_store='petsmart' 
    and deleted_by is null

返回如下响应:

productMatches =  [ { petsmart: '11562' } ]

我试图最终让我的查询返回一个带有 int 值的响应,comp_source_store如下所示:

productMatches =  [ { petsmart: '11562' }, { amazon: '231' }, { qfc: '5333' },  ]

我试图用逗号分隔我的查询以获得两个唯一计数,但查询不会运行并导致指向逗号字符的错误:

          select 
          count(distinct(comp_upc)) as petsmart from matches where 
          comp_source_store='petsmart' and deleted_by is null,

          count(distinct(comp_upc)) as amazon from matches where 
          comp_source_store='amazon' and deleted_by is null

标签: sqlpostgresqlcount

解决方案


您可以使用 group by 将每个商店放在一行中,如下所示:

select 
    comp_source_store,
    count(distinct(comp_upc)) as comp_upc_count
from matches 
where 
    comp_source_store in ('petsmart', 'amazon', 'qfc')
    and deleted_by is null
group by 
    comp_source_store

推荐阅读