简体   繁体   English

仅选择某些列仅包含特定值的ID

[英]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'. 我只想选择给定ID的所有event_type A条目都具有event_value ='sinus'的ID。 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. 在表名方面缺乏确切的细节,但您似乎想检查该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() . 使用布尔聚合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: 或者使用WHERE子句:

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 : 我会在GROUP BYHAVING子句中使用:

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';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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