1

给定一张考试结果表,其中 1 == PASS 和 0 == FAIL


ID    Name    Test   Result
--------------------
1     John    MATH   1
2     John    ENGL   1
3     Mary    MATH   1
4     Mary    PSYC   0

编辑:假设名称是唯一的。



我需要为那些1) 通过所有测试
2) 至少通过一项测试的人获取所有记录

因此,第一个查询应该返回 John 和他的所有记录,第二个查询应该返回 Mary 和她的所有记录(包括通过 PASS 的记录)。

我正在尝试对其LEFT OUTER JOIN自身进行比较并比较计数,但似乎没有得到有效的查询。


SELECT * FROM Results R1
LEFT OUTER JOIN Results R2 on R1.ID=R2.ID and R2.Result=1
WHERE ??? count of rows from R1 is compared to count of non-null rows from R2
4

4 回答 4

3

这是该EXISTS子句的“典型”练习:

至少有一个失败的结果:

select * from Results r
where exists (select * from Results rr where rr.Name=r.Name AND Result=0)

全部通过:

select * from Results r
where not exists (select * from Results rr where rr.Name=r.Name AND Result=0)

查看这些查询如何在您的数据集上工作sqlfiddle.com

于 2012-08-17T18:05:32.653 回答
2

全部通过

SELECT Name FROM Results R1
GROUP BY NAME
HAVING SUM(RESULT) = COUNT(RESULT)

有些失败了

SELECT Name FROM Results R1
GROUP BY NAME
HAVING SUM(RESULT) < COUNT(RESULT)

希望能帮助到你

编辑

全部通过

SELECT Name FROM Results R1
GROUP BY NAME
HAVING SUM(1-RESULT) = 0

有些失败了

SELECT Name FROM Results R1
GROUP BY NAME
HAVING SUM(1-RESULT) > 0

(这可能运行得更快)

于 2012-08-17T18:05:01.420 回答
1

单程

  Select Name, 
     Case failCount When 0 then 'X' Else '' End PassedAll,
     Case failCount When 0 then '' Else 'X' End FailedOneOrMore
  From (Select name, 
        Sum(Case Result when 0 Then 1 Else 0 End) failCount
        From Results R
        Group By Name) Z

要获取所有记录,只需加入此

   Select zz.Name, zz.PassedAll, zz.FailedOneOrMore,
      r.Test, r.Result 
   From (Select Name, 
             Case failCount When 0 then 'X' Else '' End PassedAll,
             Case failCount When 0 then '' Else 'X' End FailedOneOrMore
        From (Select name, 
              Sum(Case Result when 0 Then 1 Else 0 End) failCount
              From Results R
              Group By Name) Z) ZZ
       Left Join Results r On r.Name = zz.Name
于 2012-08-17T18:04:29.487 回答
0

此查询使用子查询返回已通过至少一项测试的人员的所有记录(通过和失败):

select * from Results where Name in (select Name from Results where Result = '1' group by Name);

结果不包括那些未能通过任何测试的人。

于 2012-08-17T18:38:26.857 回答