选择所有判决至少改变一半的判决

时间:2013-10-06 09:52:55

标签: sql

我有两张桌子:

case(caseId,judge,verdict)

appeal(caseId,verdict)

我想选择所有判决至少有一半时间改变的法官(例如,如果法官主持了5个案件,其中3个判决在上诉中有所改变,我想选择他)。

我尝试使用嵌套查询来解决它,但我感到困惑,因为我真的不明白如何从嵌套查询中引用外部查询。

更新:我尝试了什么(我真的不知道如何让嵌套查询只选择与外部查询相同的评判者)

SELECT DISTINCT judge
FROM case c
WHERE (SELECT COUNT(*) FROM C WHERE c.judge = case.judge) <= 2 * (SELECT COUNT(*) FROM appeal,case WHERE case.cid = appeal.cid AND case.verdict <> appeal.verdict)

3 个答案:

答案 0 :(得分:2)

可能你会尝试类似的东西:

SELECT n.judge FROM (
    SELECT s.judge, COUNT(*) AS total, COUNT(s.changed_verdict) AS changed FROM (
        SELECT c.caseId, c.judge, c.verdict, a.verdict AS changed_verdict FROM case c
            LEFT JOIN appeal a ON a.caseId = c.caseId AND a.verdict != c.verdict
    ) s
    GROUP BY s.judge
) n WHERE n.changed >= n.total / 2;

答案 1 :(得分:2)

如果我理解正确,这应该没问题:

SELECT cases.judge, SUM(appeal.verdict != cases.verdict) / COUNT(*) AS changed
FROM cases
JOIN appeal ON appeal.case_id = cases.case_id
GROUP BY cases.judge
HAVING changed > 0.5

我刚刚将case重命名为cases,以免打扰标识符转义。

答案 2 :(得分:1)

select *
from (
   select c.caseid,
          c.verdict,
          c.judge,
          count(*) over (partition by c.judge) as total_cases_per_judge,
          sum(
             case
               when (c.verdict <> coalesce(a.verdict, -1)) then 1
               else 0
             end) over (partition by c.judge) as changed_cases
   from "case" as c
     left join appeal a on a.caseid = c.caseid
) t
where changed_cases >= total_cases_per_judge/2;

case是保留关键字,您不应将其用作表名(这就是为什么我必须将其放入双引号中,否则不允许使用保留字作为标识符)