根据sql server中的条件检查列值的计数是否等于1

时间:2017-11-16 09:46:16

标签: sql sql-server join

我有两张桌子

学生

StudentId    |  StudentName
----------   |  --------------
1            |  John
2            |  Susan
3            |  Andy
4            |  Joe

StudentId    |    DepartmentId
----------   |    ------------
1            |    123
1            |    234
2            |    123
2            |    456
3            |    123
4            |    456

每个学生可以在多个部门,但我必须找到那些只在一个部门的学生,如学生3和4

任何帮助?

5 个答案:

答案 0 :(得分:2)

使用HAVINGSELECT s.StudentId,s.StudentName FROM Department d JOIN Student s ON s.StudentId=d.StudentId GROUP BY s.StudentId,s.StudentName HAVING COUNT(d.DepartmentId)=1

SELECT s.StudentId,s.StudentName
FROM Department d
RIGHT JOIN Student s ON s.StudentId=d.StudentId
GROUP BY s.StudentId,s.StudentName
HAVING COUNT(d.DepartmentId)<=1

如果你还想向不在Department表中的学生展示

LEFT JOIN

变体SELECT s.StudentId,s.StudentName FROM Student s LEFT JOIN Department d ON s.StudentId=d.StudentId GROUP BY s.StudentId,s.StudentName HAVING COUNT(d.DepartmentId)<=1

{{1}}

答案 1 :(得分:0)

只需加入他们&amp;使用Group by .. having函数

count()子句聚合起来
SELECT s.StudentId, s.StudentName
FROM student s
     JOIN Department d ON d.StudentId = s.StudentId
GROUP BY s.StudentId, s.StudentName
HAVING COUNT(d.DepartmentId) = 1;

结果:

studentid   studentname 
3           Andy        
4           Joe         

答案 2 :(得分:0)

您可以IN使用department表格组StudentId,并在子查询中使用count(Student_Id) = 1,如下所示。

SELECT *
FROM student s
WHERE s.StudentId IN (
        SELECT d.StudentId
        FROM Department d
        GROUP BY d.StudentId
        HAVING count(d.DepartmentId) = 1
        );

<强>结果:

+-----------+-------------+
| studentid | studentname |
+-----------+-------------+
|         3 | Andy        |
|         4 | Joe         |
+-----------+-------------+

<强> DEMO

答案 3 :(得分:0)

试试这个,

SELECT st.StudentId, St.StudentName
FROM student st
     JOIN Department dep ON dep.StudentId = st.StudentId
GROUP BY st.StudentId
HAVING COUNT(dep.DepartmentId) = 1;

答案 4 :(得分:0)

另一种方法是通过使用IN表来消除在开始时拥有多个系的学生,然后使用带有with cte as ( select StudentId from Department group by StudentId having count(StudentId)=1 ) select * from Students where StudentId in (select StudentId from cte) 关键字的表,例如:

@Entity
@Table(name = "my_table")
public class MyEntity {
    @OneToOne(fetch = FetchType.LAZY)
        private MyOtherEntity myOtherEntity
}