SQL - 混合AND和OR

时间:2010-02-24 16:56:27

标签: sql database sql-server-2005

我不是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)

我做错了什么?谢谢!

4 个答案:

答案 0 :(得分:4)

你需要在由AND连接的前两个布尔表达式周围添加一组parens

应该是

(...) OR
(...) 

答案 1 :(得分:4)

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

答案 2 :(得分:1)

试试这个

(SELECT COUNT(*) FROM Student s WHERE s.ClassroomID=c.ID) >30

而不是

(SELECT COUNT(*) FROM Student s WHERE s.ClassroomID=c.ID > 30)

答案 3 :(得分:0)

非常清楚你的parens。

请注意,我又添加了3组parens。

((c.[DepartmentID]=5) AND ((SELECT COUNT(*) FROM Student s WHERE s.ClassroomID=c.ID) > 30)) OR