获取公共行

时间:2012-05-28 15:48:16

标签: sql-server

我有一张表:

     Subject_ID StudyPlan_ID   
       271            2   
       279            2  
       276            2  
       279            8 
       271            8   
       267            9   
       279            9   

我希望找到Subject_ID之间的公共StudyPlan_ID,所以它是使用SqlServer 2008的279 所以请任何帮助。

1 个答案:

答案 0 :(得分:1)

如果我理解正确,您的意思是找到链接到每个StudyPlan_ID的Subject_ID。

DECLARE @Data TABLE(Subject_ID int, StudyPlan_ID int)
INSERT INTO @Data
    VALUES
        (271, 2),
        (279, 2),
        (276, 2),
        (279, 8),
        (271, 8), 
        (267, 9),
        (279, 9)

SELECT Subject_ID
FROM @Data AS a
GROUP BY Subject_ID
HAVING COUNT(Distinct StudyPlan_ID) = (SELECT COUNT(Distinct StudyPlan_ID) FROM @Data)