获取包含所有必需Column2值的不同Column1值

时间:2014-08-28 13:29:06

标签: sql sql-server-2008

我正在尝试提取包含BuntiesCandies的Jars。

Row#        Column1           Columm2
---------------------------------------       
1           Jar1              Bunties
2           Jar1              Candies
3           Jar1              Biscuits
4           Jar1              Jellies
5           Jar2              Bunties
6           Jar2              Candies
7           Jar2              Biscuits
8           Jar3              Bunties
9           Jar3              Candies
10          Jar4              Bunties
11          Jar4              Jellies

Jar1,Jar2,Jar3是所需的输出,因为这些是唯一包含BuntiesCandies的广告。

3 个答案:

答案 0 :(得分:1)

您可以使用EXISTS:

SELECT Distinct t.Column1
FROM dbo.TableName t
WHERE t.Columm2 IN ('Bunties', 'Candies')
AND EXISTS(
     SELECT 1 FROM dbo.TableName t2
     WHERE t2.Column1 = t.Column1
     AND   t2.Columm2 <> t.Columm2
     AND   t2.Columm2 IN ('Bunties', 'Candies')
)

答案 1 :(得分:1)

您可以使用GROUP BYHAVING来获得结果:

select Column1
from dbo.yourtable
where Columm2 in ('Bunties', 'Candies') 
group by Column1
having count(distinct Columm2) = 2;

您的WHERE子句将包含您要查找的值,然后GROUP BY Column1并计算Columm2中的不同值。

答案 2 :(得分:0)

SELECT DISTINCT COLUMN1, COUNT(*)
FROM TABLE
WHERE COLUMN2 IN ('BUNTIES','CANDIES')
HAVING COUNT(*)=2