[英]Select only IDs where certain columns only contains a certain value
I have the following, 我有以下内容
CREATE TABLE t (
id int,
events text, -- may be 'HR1', 'HR2', 'HR3', etc Or 'BP'
event_value int
);
events
can be HR1
/ HR2
(an id
either has HR1
or HR2
, not both), or any other event: eg `BP) events
可以是HR1
/ HR2
(一个id
具有HR1
或HR2
,而不是两者都有),也可以是任何其他事件:例如,“ BP” id
has several rows. id
都有几行。 I basically want to select IDs which have, for HR1
or HR2
(depending on which it is used for that ID), all their values in between 50 and 110. 我基本上想选择ID为
HR1
或HR2
(取决于该ID用于哪个ID)的所有ID,它们的值都在50到110之间。
The query for HR1
or HR2
returns a distinct id
and event
if all the groups values are between 50 and 110. 如果所有组值都在50到110之间,则针对
HR1
或HR2
的查询将返回不同的id
和event
。
The following table is an example: 下表是一个示例:
ID | event | event value
-----------+---------+-------------
1 'HR1' 80
1 'HR1' 90
1 'HR1' 72
1 'HR1' 91
1 'HR1' 69
1 'BP' 2.3
-
2 'HR1' 90
2 'HR1' 40
2 'HR1' 39
-
3 'HR2' 200
3 'HR2' 230
3 'HR2' 85
-
4 'HR2' 90
4 'HR2' 80
4 'HR2' 90
I want the following output: 我想要以下输出:
subject_id | event
------------+--------
1 'HR1'
4 'HR2'
I would use NOT EXISTS
and DISTINCT subject_id,event
to make it. 我会使用
NOT EXISTS
和DISTINCT subject_id,event
来做到这一点。
SELECT DISTINCT id,event
FROM t AS t1
WHERE NOT EXISTS(
SELECT 1
FROM t AS t2
WHERE (t2.event_value < 50 OR t2.event_value > 110)
AND t1.id = t2.id
AND t1.event = t2.event
)
AND t1.event in ('HR1','HR2');
Thorsten's answer is fine, but I would express it as: Thorsten的回答很好,但我将其表示为:
select subject_id,
min(event) -- only one event per subject
from mytable
where event in ('HR1', 'HR2')
group by subject_id
having min(event_value) >= 50 and
max(event_value) <= 110
order by subject_id;
This answer is no longer valid, as the OP has altered the requirement.
由于OP已更改要求,因此该答案不再有效。
No, this is not complex.
不,这并不复杂。
You want to exclude subjects for which exist HR1/2 records with a value outside the given bounds.
您要排除存在HR1 / 2记录且值超出给定范围的主题。
So use
NOT EXISTS
or
NOT IN
.
因此,请使用
NOT EXISTS
或
NOT IN
。
select * from mytable where subject_id not in ( select subject_id from mytable where event in ('HR1', 'HR2') and event_value not between 50 and 100 ) order by subject_id;
You have changed the desired output, which makes this a completely different request. 您已经更改了所需的输出,这使它成为完全不同的请求。 You want one row per subject now, an aggregation:
您现在希望每个主题一行,一个汇总:
SELECT id, event
FROM t
WHERE event in ('HR1', 'HR2')
GROUP BY id, event
HAVING count(CASE WHEN event_value NOT BETWEEN 50 AND 110 THEN 1 END) = 0
ORDER BY id;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.