无法使用“AND”运算符显示所需结果

时间:2013-05-22 20:29:56

标签: sql sql-server-2008 tsql

使用“ AND ”运算符难以获取查询以检索所需结果。需要显示firstname中完成3门课程中任何一门课程的人lastnameemailcourseIDdistrictIDNum=5,即(健康旧(courseIDNum = 11) 健康新(courseIDNum = 12))AND(PE旧(courseIDNum = 68 OR < strong> PE New(courseIDNum = 177))AND courseIDNum = 128 。请注意1112实际上是相同的课程:一个是旧课程,另一个是新课程(与68177相同,因此,districtIDNum = 5中的人只能接受一个或另一个;这就是我尝试使用(11,12)的原因。但是,它无法正常工作它返回0行。

SELECT max(p.FirstName),
       max(p.LastName),
       max(p.Email),
       max(s.CourseIDNum)
FROM People p
INNER JOIN Registration r
   on p.PeopleID = r.PeopleIdNum
INNER JOIN Section s
   on r.SectionIDNum = s.SectionID
INNER JOIN School sc
   on p.SchoolIDNum = sc.SchoolID
WHERE s.CourseIDNum IN (11, 12)
  AND s.CourseIDNum IN (68, 177)
  AND s.CourseIDNum=128
  AND sc.DistrictIDNum = 5
  AND r.Completed='Y'
group by p.PeopleID
having count(distinct s.CourseIDNum)=1

NOT 返回的行Liz M来自完成districtIDNum=12的{​​{1}}。另一方面,来自courseIDNum=195的{​​{1}}已完成Esther B;因此,她的数据应显示所有3个课程ID。数据还应显示districtIDNum=5已完成courseIDs 11, 177 and 128

以下是示例表:

的peopleid名姓电子邮件schoolIDNum
1埃丝特乙b@hotmail.com 33
2托米大号l@hotmail.com 55
3利兹中号m@hotmail.com 90

registrationID peopleIDNum sectionIDNum
22个1 40
23个2 41
24个3 132
25个1 78
26个2 52
27 1 63

sectionID courseIDNum
40个11
41个12
52个68
63个128
78个177
132 195

courseID coursename
11健康(旧)
12健康(新)
68 PE(旧)
128键盘输入
177 PE(新)
195计算

schoolID districtIDNum
33个5
55个5
90 12

2 个答案:

答案 0 :(得分:1)

您说明查询条件的方式

 s.CourseIDNum IN (11, 12)
 AND s.CourseIDNum IN (68, 177)
 AND s.CourseIDNum=128

表示CourseIDNum必须同时等于一组整数

SELECT p.FirstName,
       p.LastName,
       p.Email
FROM People p
WHERE p.PeopleID IN
(
    SELECT r.PeopleIdNum
    FROM Registration r
    INNER JOIN Section s
       on r.SectionIDNum = s.SectionID
    INNER JOIN School sc
       on p.SchoolIDNum = sc.SchoolID
    WHERE s.CourseIDNum IN (11, 12, 68, 177, 128)
      AND sc.DistrictIDNum = 5
      AND r.Completed='Y'
)

获得人员列表后,通过连接部分记录(例如herehere来检索他们的课程ID。

答案 1 :(得分:0)

WHERE s.CourseIDNum IN (11, 12)
  AND s.CourseIDNum IN (68, 177)
  AND s.CourseIDNum=128

您的这部分意味着您正在编写类似这样的查询

WHERE s.CourseIDNum IN (11,12,68,177) and courseIDNum = 128

这意味着一个案例中的CourseID num可以等于11,12,68,177,同时它应该等于128 ....这是不可能的。 所以我不确定,但尝试使用像

WHERE (s.CourseIDNum IN (11, 12,68,177)
  OR s.CourseIDNum=128)