[英]How can I return all rows for a value where at least one row meets a condition?
我正在嘗試返回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 |
+------+-----------+----------------+
如前所述,我需要返回該ID為Num_Occurrence> = 10的所有行。
謝謝!!
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的所有行。
您可以這樣做:
select t.*
from tbl t
where exists (select 1
from tbl t2
where t2.id = t.id and t2.id >= 10
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.