如何编写查询以查找未处理的记录

How to write a query to find a record which is not processed

我正在尝试从具有 2 列的 table A 编写查询:

ID , STATUS

状态可以是PROCESSING, NOTPROCESSED, FAILED, SUCCESS

成功处理一条记录后,将在数据库中创建一条新记录,其状态为 PROCESSED,ID 与之前的 NOTPROCESSED 记录相同。

数据库中的示例记录需要:

1      NOTPROCESSED
2      PROCESSED
1      PROCESSED
3      NOTPROCESSED
4      NOTPROCESSED
2      PROCESSED
3      NOTPROCESSED
4      NOTPROCESSED

NOTPROCESSED 的记录可能显示为重复。

我必须查询 NOTPROCESSED

的记录
3      NOTPROCESSED
4      NOTPROCESSED

写查询变得很混乱。

任何人都可以帮助逻辑。

id 分组,只取那些没有状态记录的组 PROCESSED

select id
from your_table
group by id
having sum(case when status = 'PROCESSED' then 1 else 0 end) = 0

或者只获取只有一种状态的

having count(distinct status) = 1

或按字母顺序使用最高状态

having max(status) = 'NOTPROCESSED'

这里有几个选项:

select distinct id from A where id not in (
  select id from A where status = 'PROCESSED'
);

select distinct id from A natural left join (
  select id from A where status = 'PROCESSED'
) as B where B.id is null;

您可以使用 not exists 来获取此输出。

select distinct a.id,a.status
  from table a
 where a.status='NOTPROCESSED'
   and not exists (select null
                     from table b
                    where b.id=a.id
                      and b.status='PROCESSED')

您可以使用解析函数如下:

select * from
(select t.*, count(case when status = 'PROCESSED' then 1 end)
                   over (partition by ID) as cnt
from your_table t) t
where status = 'NOTPROCESSED' and cnt = 0