【问题标题】:postgresql get unique count for multiple valuespostgresql 获取多个值的唯一计数
【发布时间】:2021-04-11 15:29:47
【问题描述】:

我是 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' } ]

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

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

【问题讨论】:

    标签: sql postgresql count


    【解决方案1】:

    您可以使用 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
    

    【讨论】:

      【解决方案2】:

      使用条件聚合:

      select count(distinct comp_upc) filter (where comp_source_store = 'petsmart') as petsmart,
             count(distinct comp_upc) filter (where comp_source_store = 'amazon') as amazon,
             . . .  -- and so on
      from matches
      where deleted_by is null;
      

      您可能会发现将结果放在行中更容易:

      select comp_source_store, count(distinct comp_upc) as cnt
      from matches
      where deleted_by is null
      group by comp_source_store
      

      【讨论】:

        猜你喜欢
        • 2021-04-25
        • 1970-01-01
        • 2020-09-22
        • 1970-01-01
        • 1970-01-01
        • 2020-11-11
        • 1970-01-01
        • 2011-06-22
        • 1970-01-01
        相关资源
        最近更新 更多