![](/img/trans.png)
[英]Query to update 1 column with no condition and another column only if certain condition is met
[英]Count only if condition on another column met
只有满足其他列条件时,我才需要计算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),我必须仅COUNT条符合条件的ID。 条件很简单:键<>'step0',因此我的COUNT脚本应返回值3。
如果我试试
COUNT ID
FROM myTable
WHERE key <> 'step0'
它返回错误的值,因为WHERE子句在COUNT之前应用
任何想法都赞赏。
这是一个不需要嵌套聚合函数且不需要子查询的方法:
select (count(distinct id) -
count(distinct case when key = 'step0' then id end)
)
from mytable;
尝试使用不存在的相关子查询
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
例如使用反向逻辑,来自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。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.