gpt4 book ai didi

SQL - 混合 AND 和 OR

转载 作者:太空狗 更新时间:2023-10-30 01:59:53 27 4
gpt4 key购买 nike

我不是 SQL 专家。我正在使用 SQL Server 2005,我正在尝试弄清楚如何构造一个查询,以便它可以满足多种要求。我有两个表定义如下:

Classroom
- ID
- DepartmentID
- TeacherName
- RoomNumber

Student
- ID
- Name
- ClassroomID

我正在尝试构建一个查询,“给我部门 [x] 或部门 [y] 中超过 30 名学生的教室,并给我部门 [w] 或部门 [z] 中的教室有超过 40 名学生。我对如何在我的 SQL 中正确混合 AND 和 OR 感到困惑。目前,我正在尝试以下操作:

SELECT
c.RoomNumber,
c.TeacherName
FROM
Classroom c
WHERE
c.[DepartmentID]=5 AND (SELECT COUNT(*) FROM Student s WHERE s.ClassroomID=c.ID > 30) OR
c.[DepartmentID]=6 AND (SELECT COUNT(*) FROM Student s WHERE s.ClassroomID=c.ID > 30) OR
c.[DepartmentID]=7 AND (SELECT COUNT(*) FROM Student s WHERE s.ClassroomID=c.ID > 40) OR
c.[DepartmentID]=8 AND (SELECT COUNT(*) FROM Student s WHERE s.ClassroomID=c.ID > 40)

我做错了什么?谢谢!

最佳答案

SELECT  c.id
FROM Classroom c
JOIN Students s
ON s.Classroom = c.Id
WHERE DepartmentID IN ('X', 'Y', 'W', 'Z')
GROUP BY
c.id, c.DepartmentID
HAVING COUNT(*) >= CASE WHEN DepartmentID IN ('X', 'Y') THEN 30 ELSE 40 END

关于SQL - 混合 AND 和 OR,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2327803/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com