我有以下内容,
CREATE TABLE t (
id int,
events text, -- may be 'HR1', 'HR2', 'HR3', etc Or 'BP'
event_value int
);
events
可以是HR1
/ HR2
(id
具有HR1
或HR2
,但不能同时具有两者)或任何其他事件:例如`BP)id
都有几行。我基本上想选择HR1
或HR2
(取决于该ID使用哪个ID)的所有ID都在50到110之间的ID。
如果所有组的值都在50到110之间,则对HR1
或HR2
的查询将返回不同的id
和event
。
下表是一个示例:
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
我想要以下输出:
subject_id | event
------------+--------
1 'HR1'
4 'HR2'
答案 0 :(得分:2)
我会用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');
答案 1 :(得分:2)
索尔斯滕的答案很好,但我将其表达为:
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;
答案 2 :(得分:1)
此答案不再有效,因为OP更改了要求。
<罢工>
不,这并不复杂。您要排除存在HR1 / 2记录且值超出给定范围的主题。因此,请使用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;
答案 3 :(得分:1)
您已经更改了所需的输出,这使此请求完全不同。您现在想要每个主题一行,一个汇总:
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;