【问题标题】:how to select the unique id count for repeated id that have a specific value如何为具有特定值的重复 id 选择唯一 id 计数
【发布时间】:2020-09-21 10:33:48
【问题描述】:

例如,如果我有这张桌子

 report_date     id    customerCount    orderNr
  2020-02-20    123        12              10
  2020-02-19    123        18              11
  2020-02-18    123        0               12
  2020-02-20    321        0               0
  2020-02-19    321        0               0
  2020-02-18    321        0               0
  2020-02-20    456        17              13
  2020-02-19    456        0               0
  2020-02-18    456        15              14
  2020-02-20    654        0               0
  2020-02-19    654        0               0
  2020-02-18    654        0               0

我想选择所有行都是 customerCount = 0 和 orderNr = 0 的 id 计数

【问题讨论】:

    标签: sql postgresql group-by count having-clause


    【解决方案1】:

    要列出所有ids,您可以使用聚合和having。布尔聚合可以方便地表达约束:

    select id
    from mytable
    group by id
    having bool_and(customerCount = 0) and bool_and(order_nr = 0)
    

    如果要统计有多少ids满足条件,可以再加一层聚合:

    select count(*) cnt
    from (
        select id
        from mytable
        group by id
        having bool_and(customerCount = 0) and bool_and(order_nr = 0)
    ) t
    

    【讨论】:

      【解决方案2】:

      一种方法使用两个级别的聚合:

      select count(*)
      from (select id
            from t
            group by id
            having max(customerCount) = 0 and max(orderNr) = 0
           ) i;
      

      注意:这假设值永远不会为负,考虑到示例值和命名,这似乎很合理。

      另一种方法使用not exists

      select count(distinct id)
      from t
      where not exists (select 1
                        from t t2
                        where t2.id = t.id and
                              (t2.customerCount <> 0 or t.orderNr <> 0)
                       );
      

      【讨论】:

        【解决方案3】:
        select count(table.id)
        from table 
        where customerCount = 0 and orderNr = 0
        group by table.id
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-12-11
          • 1970-01-01
          • 1970-01-01
          • 2021-01-30
          • 2015-11-15
          相关资源
          最近更新 更多