【问题标题】:Multiple rows with same ID number but different status values - How do I select out specific statuses to grab IDs具有相同 ID 号但状态值不同的多行 - 如何选择特定状态来获取 ID
【发布时间】:2019-12-19 05:53:01
【问题描述】:

我有一个表,其中包含一个 ID 字段和一个状态字段,该字段可以具有多种状态类型,例如“活动”“最终”“失败”“cmets”。我希望能够选择没有与许可证号码相关的“最终”状态的许可证号码,或者至少没有四个“活动”状态。我知道我需要使用 COUNT(),但我不知道如何让它按许可证号过滤。

最后会标记 permitnum 777 的表格示例:

PermitNum Status  
222       active  
222       active  
222       finaled  
444       active  
444       active  
444       active  
444       active  
777       active  
777       fail  
777       active  
777       active  

我一直在使用 COUNT() 根据 WHERE 子句获取状态字段的通用计数,但我不知道如何将其与许可证编号联系起来。

【问题讨论】:

    标签: sql group-by aggregation


    【解决方案1】:

    您可以使用条件聚合。获取被标记的值:

    select permitno
    from t
    group by permitno
    having sum(case when status = 'finaled' then 1 else 0 end) > 0 and
           sum(case when status = 'active' then 1 else 0 end) < 4;
    

    要获得“好”许可证:

    select permitno
    from t
    group by permitno
    having sum(case when status = 'finaled' then 1 else 0 end) = 0 or
           sum(case when status = 'active' then 1 else 0 end) >= 4;
    

    【讨论】:

    • 根据OP,您需要将第一个HAVING子句更改为status = 'finaled'而不是failed。否则,我认为您的第二个查询是正确的。
    • 这很好,初始测试工作正常。谢谢戈登。
    【解决方案2】:

    您可以使用not exists 并通过having count(case when Status='active' then 1 end)&lt;4 限制您的下一个条件:

    select PermitNum 
      from tab t
     where not exists ( select 0 from tab where status='finaled' and PermitNum = t.PermitNum  )
     group by PermitNum
    having count(case when Status='active' then 1 end)<4
    

    Demo

    【讨论】:

      猜你喜欢
      • 2013-05-29
      • 1970-01-01
      • 2021-03-20
      • 2021-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-23
      相关资源
      最近更新 更多