[英]Check the count of column value is equal to one based on condition in sql server
I have two tables 我有两张桌子
Student 学生
StudentId | StudentName
---------- | --------------
1 | John
2 | Susan
3 | Andy
4 | Joe
Department 部
StudentId | DepartmentId
---------- | ------------
1 | 123
1 | 234
2 | 123
2 | 456
3 | 123
4 | 456
Each student can be in multiple departments but I have to find those students which are only in one department like student 3 and 4 每个学生可以在多个系中,但是我必须找到那些只在一个系中的学生,例如学生3和4
Any help? 有什么帮助吗?
Use GROUP BY
and HAVING
使用GROUP BY
和HAVING
SELECT 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
And if you also want to show students which not in Department table 如果您还想向学生显示不在部门表中的内容
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
Variant with LEFT JOIN
有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
Simply join them & aggregate them by Group by
clause with having
.. count()
function 只需加入它们并通过having
.. count()
函数的Group by
子句将它们聚合
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;
Result : 结果:
studentid studentname
3 Andy
4 Joe
You can use IN
with department
table group by StudentId
alongwith having count(Student_Id) = 1
in sub-query as below. 您可以将IN
与带有StudentId
department
表组一起使用,并且在以下子查询中具有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
);
Result: 结果:
+-----------+-------------+
| studentid | studentname |
+-----------+-------------+
| 3 | Andy |
| 4 | Joe |
+-----------+-------------+
Try this, 尝试这个,
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;
Another approach is to eliminate the students having multiple departments at the beginning by using a cte
table, then use the table with IN
keyword like: 另一种方法是通过使用cte
表消除一开始具有多个系的学生,然后使用带有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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.