拥有基于另一列的不同计数的组

时间:2018-04-15 09:07:19

标签: sql sql-server

我有一张表如下:

+-------------+-----------+------+
| GroupNumber | TeamName  | Goal |
+-------------+-----------+------+
|           1 | Sales     | ABC  |
|           1 | Sales     | ABC  |
|           1 | Sales     | ABC  |
|           1 | Design    | XYZ  |
|           2 | Design    | XYZ  |
|           2 | Sales     | XYZ  |
|           2 | technical | XYZ  |
|           2 | Support   | XYZ  |
|           3 | Sales     | XYZ  |
|           3 | Sales     | XYZ  |
|           3 | Sales     | XYZ  |
+-------------+-----------+------+

我想只输出具有大于3的唯一团队的组。 只有第2组具有此条件,因此输出为:

预期产出:

+-------------+-----------+------+
| GroupNumber | TeamName  | Goal |
+-------------+-----------+------+
|           2 | Design    | XYZ  |
|           2 | Sales     | XYZ  |
|           2 | technical | XYZ  |
|           2 | Support   | XYZ  |
+-------------+-----------+------+

不确定如何在子查询中使用它

SELECT count(Distinct(TeamName))
  FROM mytable
  group by [GroupNumber]
  HAVING COUNT(Distinct[TeamName])>3

2 个答案:

答案 0 :(得分:1)

只需将其放入子查询中:

select * 
from mytable
where [GroupNumber] in
 (
   SELECT [GroupNumber]
   FROM mytable
   group by [GroupNumber]
   HAVING COUNT(Distinct[TeamName])>3
 )

答案 1 :(得分:1)

请尝试

 SELECT *
 FROM mytable where GroupNumber in (select GroupNumber 
 FROM mytable group by TeamName
 HAVING COUNT(TeamName)>3)