选择包含组中所有元素的每一行

时间:2019-03-18 01:53:17

标签: sql sql-server

[TYPE]列具有A或B或C。我想选择表中所有A,B,C的名称列表。

enter image description here

结果

enter image description here


    -- dealing with count
    select name from tempso group by name 
    having count(*) = (select count(distinct type) from tempso);

    -- dealing with specifying elements
    select name from tempso group by name 
    having type in all('A', 'B', 'C');

实际上,我想使用第二种方法来执行此操作,因为TYPE A,B,C具有子类型,因此存在重复的风险,但是我在下面遇到了此错误。

Msg 156, Level 15, State 1, Line 10 syntax error 'all'...

有什么办法吗?

3 个答案:

答案 0 :(得分:1)

您可以使用group byhaving

select name
from t
group by name
having count(*) = (select count(distinct type) from t);

这假设表中没有重复name / type行。

编辑:

如果您只想检查A / B / C,则:

select name
from t
where type in ('A', 'B', 'C')
group by name
having count(*) = 3;

或者:

having count(distinct type) = 3

如果表中有重复项。

答案 1 :(得分:0)

您使用的无效函数'all'。并且它在HAVING子句中也无效。因此,请尝试此操作。

SELECT name,count(*)  AS cnt FROM tempso 
WHERE [type] in ('A', 'B', 'C')
GROUP BY name HAVING count(Name) >= 3

答案 2 :(得分:0)

从@table中选择名称,其中类型IN('A','B','C')按名称具有count(Name)> = 3

分组