【问题标题】:How to look for missing rows within a group?如何在组中查找缺失的行?
【发布时间】:2019-06-26 22:33:55
【问题描述】:

考虑以下数据。我试图找出在特定 RequestID 中存在Attempt: 0,但缺少Attempt: 2 的情况。

我尝试使用WHERE 谓词查找Attempt: 0 并在子查询中执行NOT EXISTS ... Attempt: 2,但它没有返回正确的数据。

如何找到缺少Attempt: 2 的RequestID?

ID      Message       RequestID
635828  Attempt: 0    1
635968  Attempt: 1    1
641085  Attempt: 2    1
641230  Attempt: 3    1
643859  Attempt: 0    2
645991  Attempt: 1    2
650255  Attempt: 3    2
652388  Attempt: 0    3
654520  Attempt: 1    3
658785  Attempt: 3    3

【问题讨论】:

  • 查找“差距和岛屿”以获得一些想法。
  • 没有时间给出一个完整的解决方案,但是看看窗口函数和滞后/领先

标签: sql sql-server sql-server-2016


【解决方案1】:

你可以像这样使用not exists

select t.*
from t
where t.message = 'Attempt: 0' and
      not exists (select 1
                  from t t2
                  where t2.requestid = t.requestid and
                        t2.message = 'Attempt: 2'
                 );

另一种可能性是聚合:

select requestid
from t
where message in ('Attempt: 0', 'Attempt: 2')
group by requestid
having sum(case when message = 'Attempt: 2' then 1 else 0 end) = 0;

【讨论】:

    猜你喜欢
    • 2019-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-12
    相关资源
    最近更新 更多