鉴于下表:
id | value
---+---------
1 | 1
1 | 0
1 | 3
2 | 1
2 | 3
2 | 5
3 | 2
3 | 1
3 | 0
3 | 1
我想要下表:
id | value
---+---------
1 | 1
1 | 0
1 | 3
3 | 2
3 | 1
3 | 0
3 | 1
该表包含ids
,其最小value
为0。
我尝试过使用exist
和having
,但没有成功。
答案 0 :(得分:1)
试试这个:
select * from foo where id in (SELECT id FROM foo GROUP BY id HAVING MIN(value) = 0)
或那个(带窗口功能)
select * from
(select *,min(value) over (PARTITION BY id) min_by_id from foo) a
where min_by_id=0
答案 1 :(得分:0)
如果我理解正确,那么这是一个相当简单的having
条款:
=# SELECT id, MIN(value), MAX(value) FROM foo GROUP BY id HAVING MIN(value) = 0;
id | min | max
----+-----+-----
1 | 0 | 3
3 | 0 | 2
(2 rows)
我是否错过了让它变得更复杂的东西?
答案 2 :(得分:0)
看起来在WHERE或HAVING中无法使用窗口功能。以下是基于JOIN的解决方案。
SQL看起来像这样。
SELECT a.*
FROM a_table AS a
INNER JOIN a_table AS value ON a.id = b.id
WHERE b.value = 0;