如何返回至少有一行符合条件的值的所有行?

时间:2016-12-12 02:32:15

标签: sql postgresql

我尝试返回ID为其中一个或多个Num_Occurrence行为> = 10的所有行。

以下是原始数据的示例:

+------+-----------+----------------+
| ID   | YearMonth | Num_Occurrence |
+------+-----------+----------------+
| 1234 | 201601    | 7              |
+------+-----------+----------------+
| 1234 | 201602    | 8              |
+------+-----------+----------------+
| 1234 | 201603    | 12             |
+------+-----------+----------------+
| 1234 | 201604    | 9              |
+------+-----------+----------------+
| 9898 | 201601    | 9              |
+------+-----------+----------------+
| 9898 | 201602    | 8              |
+------+-----------+----------------+
| 9898 | 201603    | 9              |
+------+-----------+----------------+
| 9898 | 201604    | 6              |
+------+-----------+----------------+

这是所需的输出:

+------+-----------+----------------+
| ID   | YearMonth | Num_Occurrence |
+------+-----------+----------------+
| 1234 | 201601    | 7              |
+------+-----------+----------------+
| 1234 | 201602    | 8              |
+------+-----------+----------------+
| 1234 | 201603    | 12             |
+------+-----------+----------------+
| 1234 | 201604    | 9              |
+------+-----------+----------------+

我知道以下内容不起作用:

SELECT *
FROM tbl
WHERE Num_Occurrence >= 10

因为那只会返回这一行:

+------+-----------+----------------+
| ID   | YearMonth | Num_Occurrence |
+------+-----------+----------------+
| 1234 | 201603    | 12             |
+------+-----------+----------------+

如前所述,我需要为NY_Occurrence> = 10的任何ID返回所有行。

谢谢!

2 个答案:

答案 0 :(得分:5)

SELECT * FROM [tbl] t1
WHERE EXISTS (SELECT * FROM [tbl] t2
              WHERE t2.ID = t1.id
              AND t2.Num_Occurrence >= 10);

" EXISTS"这里使用子句查询所有具有Num_Occurrence> = 10的行,然后将其与完整表进行比较,以获得具有匹配ID的所有行。

答案 1 :(得分:2)

您可以这样做:

select t.*
from tbl t
where exists (select 1
              from tbl t2
              where t2.id = t.id and t2.id >= 10
             );