簡體   English   中英

僅選擇某些列僅包含特定值的ID

[英]Select only IDs where a certain column only contains a certain value

我有下表示例:

輸入:

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

輸出:

ID 
---
 1
 3

我只想選擇給定ID的所有event_type A條目都具有event_value ='sinus'的ID。 我怎樣才能做到這一點?

非常感謝!

在表名方面缺乏確切的細節,但您似乎想檢查該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')

然后需要根據所需的輸出對結果進行分組/匯總,問題中未顯示。

使用布爾聚合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) 

或者使用WHERE子句:

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

單程:

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

我會在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