【问题标题】:SQL duplicate counting headacheSQL重复计数头痛
【发布时间】:2019-02-11 16:33:39
【问题描述】:

我有一个不知道如何克服的问题,非常感谢一些方向。

示例数据

Device  Project     status
a111    101     Ready
a222    102     Finished
a333    103     Ready
a444    104     Ready
a555    105     Ready
a111    106     Started
a111    107     Ready
a555    108     Started

我正在寻找一种方法来计算处于“就绪”状态的设备数量。但是,当谈到“就绪”时,我只想计算一次,如果该设备在另一个项目中的状态不是“就绪”,则不计算它

逻辑 如果在一个或多个项目中准备好 = 计数一次 如果在一个项目中准备好但在任何其他项目中具有不同的状态 = 不计入

正确的结果应该只显示 2 为“就绪”; 'a333' 和 'a444'。

SELECT
'Ready' AS Header
, status
, count(distinct device)
FROM my_table
WHERE
project BETWEEN'101' AND '110' 
GROUP BY status

【问题讨论】:

    标签: sql oracle duplicates


    【解决方案1】:

    您可以将这样的SQL Select statementHAVING 子句一起使用:

    select device  
      from tab 
     group by device
     having sum(case when status = 'Ready' then 1 else 0 end ) =  count(device);
    
     DEVICE
     ------
     a444
     a333
    

    【讨论】:

      【解决方案2】:

      如果您的设备所有状态都准备就绪,那么一种方法使用group byhaving

      select device
      from my_table t
      group by device
      having min(status) = max(status) and min(status) = 'Ready'; 
      

      【讨论】:

        【解决方案3】:

        你可以使用not exists

        select t.*
        from table t
        where not exists (select 1 from table t1 where t1.device = t.device and t1.status <> 'Ready');
        

        【讨论】:

          【解决方案4】:

          我认为在这种情况下,表格减法将是一种很好的技术。首先使用 distinct 选择:

          select distinct(device)
            from my_table
            where status= 'Ready'
          Minus
          select distinct(device)
            from my_table
            where status <> 'Ready'
          ;
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2015-09-18
            • 2012-07-29
            • 1970-01-01
            • 2014-06-09
            • 1970-01-01
            • 2011-03-19
            • 2016-10-27
            相关资源
            最近更新 更多