返回所有匹配的记录以及至少一个不匹配的所有记录

时间:2012-08-17 17:56:47

标签: sql tsql inner-join self-join

给出一个考试结果表,其中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 个答案:

答案 0 :(得分:3)

这是一个海报孩子"练习EXISTS条款:

在leasr一个失败的结果:

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)

了解这些查询如何对您的数据集at sqlfiddle.com起作用。

答案 1 :(得分: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

(这可能会跑得更快)

答案 2 :(得分: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

答案 3 :(得分:0)

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

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

结果排除那些未能通过任何测试的人。