返回字段具有指定计数的行

时间:2015-05-20 16:08:52

标签: sql count

我有一张桌子(DF)

+----+------+-----+
| ID |  PT  | AVG |
+----+------+-----+
| A  | 1.00 | 2.5 |
| A  | 2.00 | 3.5 |
| B  | 1.00 | 2.8 |
| B  | 2.00 | 2.6 |
| B  | 3.00 | 3.9 |
+----+------+-----+

我正在尝试编写一个简单的SQL语句来提取具有3个点的ID。

我尝试了这两个陈述,但我做错了

1. Returns all rows again

SELECT * FROM DF
WHERE PT BETWEEN '1.000' AND '3.000' 

2. Returns counts of rows

SELECT * FROM DF b    
WHERE b.PT=(SELECT COUNT(DISTINCT A.PT) FROM DF A WHERE A.ID=B.ID)

我想要的输出是:

+----+------+-----+
| ID |  PT  | AVG |
+----+------+-----+
| B  | 1.00 | 2.8 |
| B  | 2.00 | 2.6 |
| B  | 3.00 | 3.9 |
+----+------+-----+  

2 个答案:

答案 0 :(得分:1)

SELECT *
FROM YourTable
WHERE ID IN (SELECT ID
             FROM YourTable
             GROUP BY ID
             HAVING COUNT(*) = 3);

答案 1 :(得分:1)

首先需要找出哪些组有三行计数。您可以使用GROUP BYHAVING子句来完成此操作:

SELECT id
FROM myTable
GROUP BY id
HAVING COUNT(*) = 3;

HAVING子句用于有关聚合的条件,请不要使用WHERE子句。获得这些值后,您可以返回并从表格中选择id列为IN上面结果集的所有行:

SELECT *
FROM myTable
WHERE id IN(
   SELECT id
   FROM myTable
   GROUP BY id
   HAVING COUNT(*) = 3);

以下是使用示例数据的SQL Fiddle示例。