[英]Count only if condition on another column met
I have to count IDs only if other columns condition met. 只有满足其他列条件时,我才需要计算ID。 IDs are not unique, as may incluse several steps.
ID不是唯一的,可能包括几个步骤。
Table looks like: 表看起来像:
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
In the example I have 5 IDs (but in real table thousands of them), and I have to COUNT only IDs where condition met. 在示例中,我有5个ID(但在实际表中有数千个ID),我必须仅COUNT条符合条件的ID。 Condition is pretty simple: key <> 'step0', thus my COUNT script should return value of 3.
条件很简单:键<>'step0',因此我的COUNT脚本应返回值3。
If I try 如果我试试
COUNT ID
FROM myTable
WHERE key <> 'step0'
it returns wrong value, as WHERE clause applies prior COUNT 它返回错误的值,因为WHERE子句在COUNT之前应用
Any ideas appreciated. 任何想法都赞赏。
Here is a method that doesn't require nesting aggregation functions and doesn't require a subquery: 这是一个不需要嵌套聚合函数且不需要子查询的方法:
select (count(distinct id) -
count(distinct case when key = 'step0' then id end)
)
from mytable;
Try using correlated subquery with not exists 尝试使用不存在的相关子查询
select count(distinct ID)
from tablename a
where not exists (select 1 from tablename b where a.id=b.id and key = 'step0')
use distinct 使用不同
select COUNT (distinct ID)
FROM myTable
WHERE ID not in ( select id from myTable where key = 'step0' and id is not null)
Use grouping with having clause 使用带有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
eg use reverse logic, come from key = 'step0'
例如使用反向逻辑,来自
key = 'step0'
This should work: 这应该工作:
SELECT COUNT(COUNT(DISTINCT id)) num_ids
FROM your_table
GROUP BY id
HAVING MIN(CASE WHEN key = 'step0' THEN key END) IS NULL;
The outer COUNT
applies to the whole query including the aggregation of the COUNT(DISTINCT id)
- remove it, and you'd see three rows with a value of 1. 外部
COUNT
适用于整个查询,包括COUNT(DISTINCT id)
的聚合 - 删除它,您将看到三行值为1。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.