简体   繁体   中英

Count only if condition on another column met

I have to count IDs only if other columns condition met. IDs are not unique, as may incluse several steps.

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. Condition is pretty simple: key <> 'step0', thus my COUNT script should return value of 3.

If I try

COUNT ID
FROM myTable
WHERE key <> 'step0'

it returns wrong value, as WHERE clause applies prior 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

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'

Demo

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM