简体   繁体   中英

Select only IDs where a certain column only contains a certain value

I have the following table example:

Input:

ID | event_type | event_value | time
---+------------+-------------+-------
1  |     A      |   sinus     | 14:23  <- select ID = 1
1  |     A      |   sinus     | 15:22
1  |     B      |   low WC    | 15:22
1  |     A      |   sinus     | 16:22
1  |     C      |   RX OK     | 17:22
.
2  |     A      |   sinus     | 14:23  
2  |     A      |  arrhytm    | 15:22 <- DON'T select ID = 2
2  |     B      |   low WC    | 15:22
2  |     A      |   sinus     | 16:22
.
3  |     A      |   sinus     |  12:32 <- select ID = 3
3  |     B      |   WC ok     |  13:23
3  |     C      |   ph ok     |  13:40
3  |     A      |   sinus     |  13:33
3  |     A      |   sinus     |  14:22

Output:

ID 
---
 1
 3

I want to select only the IDs where ALL of the event_type A entries, for a given ID, have event_value = 'sinus'. How can I do this?

Many thanks!

Lacking a bit of specifics in terms of table names to be precise, but you appear to want to check for a lack of existence of anything else for that ID / Event_type.

SELECT * 
FROM yourTable a
WHERE a.event_type = 'A' 
AND not exists (SELECT 1 
                  FROM yourTable b 
                  WHERE a.ID = b.ID 
                  AND a.event_type = b.event_type 
                  AND b.event_value <> 'sinus')

The results then need to be grouped / aggregated based on what your needed output is, it was not shown in the question.

Use the boolean aggregate bool_and() .

with my_table(id, event_type, event_value, time) as (
values
    (1, 'A', 'sinus', '14:23'),
    (1, 'A', 'sinus', '15:22'),
    (1, 'B', 'low WC', '15:22'),
    (1, 'A', 'sinus', '16:22'),
    (1, 'C', 'RX OK', '17:22'),
    (2, 'A', 'sinus', '14:23'),
    (2, 'A', 'arrhytm', '15:22'),
    (2, 'B', 'low WC', '15:22'),
    (2, 'A', 'sinus', '16:22')
)

select id
from my_table
group by id
having bool_and(event_type <> 'A' or event_value = 'sinus')

 id 
----
  1
(1 row) 

Alternatively with WHERE clause:

select id
from my_table
where event_type = 'A'
group by id
having bool_and(event_value = 'sinus')

One way:

 Select id from  table 
 where event_type ='A' 
 group by id 
 having 
 min(event_value) = 'sinus'
 and 
 max(event_value)  = 'sinus'

I would use GROUP BY with HAVING clause :

select t.id
from table t
where t.event_type = 'A'
group by t.id
having min(t.event_value) = max(t.event_value) and min(t.event_value) = 'sinus';

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