我有下表示例:
输入:
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
我只想选择所有 event_type A 条目的 ID,对于给定的 ID,event_value = 'sinus'。 我该怎么做?
非常感谢!
最佳答案
使用 bool 聚合 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')
关于sql - 仅选择特定列仅包含特定值的 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51964363/