sql - 仅选择特定列仅包含特定值的 ID

标签 sql postgresql select

我有下表示例:

输入:

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/

相关文章:

sql - 在 H2 SELECT 查询中首先对 NULL 进行排序

mysql - 将一列的值复制到新表

sql - case 语句中 "then"处或附近的语法错误

ruby-on-rails - Rails 网页有一个重定向循环 ERR_TOO_MANY_REDIRECTS

linux - 从另一个 linux 服务器连接 linux 平台中的 postgres 服务器

选择语句 channel 示例

python - 选择多于 C 列中值大于 V 的行

mysql - MySQL 中的回归分析

mysql - 根据第一个记录值获取行

sql - 获取表中下一行的值总和