0

我有两张桌子:

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)
4

3 回答 3

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;
于 2013-10-06T09:58:31.797 回答
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

我只是重命名casecases不打扰标识符转义。

于 2013-10-06T10:08:32.720 回答
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是保留关键字,您不应该将其用作表名(这就是为什么我必须将其放在双引号中,否则保留字不允许用作标识符)

于 2013-10-06T09:59:27.393 回答