Sql 仅当满足另一列上的条件时计数

Sql 仅当满足另一列上的条件时计数,sql,oracle,Sql,Oracle,只有在满足其他列条件时,我才必须计算ID。ID不是唯一的,可能包括几个步骤 表如下所示: rownum | ID | key | result 1 |100 | step1 | accepted 2 |100 | step2 | accepted 3 |100 | step3 | transfer 4 |101 | step0 | accepted 5 |101 | step1 | accepted 6 |101 | step2

只有在满足其他列条件时,我才必须计算ID。ID不是唯一的,可能包括几个步骤

表如下所示:

rownum | ID | key   | result

1      |100 | step1 | accepted
2      |100 | step2 | accepted
3      |100 | step3 | transfer
4      |101 | step0 | accepted
5      |101 | step1 | accepted
6      |101 | step2 | rejected
7      |102 | step0 | accepted
8      |102 | step1 | accepted
9      |103 | step1 | rejected
10     |104 | step1 | rejected
11     |104 | step1 | rejected
12     |104 | step1 | rejected
在这个示例中,我有5个ID(但在实际表中有数千个),并且我必须只计算满足条件的ID。条件非常简单:键“step0”,因此我的COUNT脚本应该返回值3

如果我尝试

COUNT ID
FROM myTable
WHERE key <> 'step0'
计数ID
从myTable
何处键“step0”
它返回错误的值,因为WHERE子句应用了优先计数


任何想法都值得赞赏。

尝试使用不存在的相关子查询

select count(distinct ID)
from tablename a 
   where not exists (select 1 from tablename b where a.id=b.id and key = 'step0')
使用不同的

select COUNT (distinct ID)
FROM myTable
WHERE ID not in ( select id from myTable where key = 'step0' and id is not null)

将分组与having子句一起使用

select sum(count(distinct ID)) as "Count"
  from myTable
 group by ID
 having sum(case when key = 'step0' then 1 else 0 end)=0;
-- or "having sum( decode(key,'step0',1,0) ) = 0" is also possible specific to Oracle

Count
-----
  3
e、 g.使用反向逻辑,来自
key='step0'

这应该可以:

SELECT COUNT(COUNT(DISTINCT id)) num_ids
FROM   your_table
GROUP BY id
HAVING MIN(CASE WHEN key = 'step0' THEN key END) IS NULL;

外部
COUNT
应用于整个查询,包括
COUNT(DISTINCT id)
的聚合-将其删除,您将看到三行值为1。

以下是一个不需要嵌套聚合函数和子查询的方法:

select (count(distinct id) -
        count(distinct case when key = 'step0' then id end)
       )
from mytable;

您是否在对没有key=step0行的ID进行计数?