加入派生表postgres

时间:2015-06-12 03:10:18

标签: sql postgresql derived

我有4张桌子:

  • 能力:明显的能力清单,静态和图书馆
  • 能力等级:是指一组相关的能力,并且具有我正在测试的许多能力
  • call_competency:已记录指定能力的所有“来电”的列表
  • competency_review_status:证明每个call_competency是否已经过审核

现在我正在尝试编写此查询以计算总数并吐出能力,ID以及用户是否已达到限制。除了添加用户之外,一切都有效。我不确定我做错了什么,一旦我在where子句中限制用户的通话能力,我得到一个小的子集,只有在我想要整个能力列表时才返回call_competency。

未达到的能力应该是假的,记录的适当数字是真的。能力表中的完整列表。

我添加了派生表,不确定这是否正确,显然它运行不正常,不确定我做错了什么而且我在浪费时间。任何帮助非常感谢。

SELECT comp.id, comp.shortname, comp.description,
       CASE WHEN sum(CASE WHEN crs.grade = 'Pass' THEN 1 ELSE CASE WHEN crs.grade = 'Fail' THEN -1 ELSE 0 END END) >= comp_l.competency_break_level
       THEN TRUE ELSE FALSE END
FROM competencies comp
INNER JOIN competency_levels comp_l  ON comp_l.competency_group = comp.competency_group
LEFT OUTER JOIN (
  SELECT competency_id 
  FROM call_competency
  WHERE call_competency.user_id IN (
    SELECT users.id FROM users WHERE email= _studentemail
  )
) call_c ON call_c.competency_id = comp.id
LEFT OUTER JOIN competency_review_status crs ON crs.id = call_competency.review_status_id
GROUP BY comp.id, comp.shortname, comp.description, comp_l.competency_break_level
ORDER BY comp.id;

1 个答案:

答案 0 :(得分:1)

(从臀部拍摄,无需安装测试)

看起来下面应该可以解决问题。您显然已将某些连接混合在一起,其中一列来自未引用的关系。此外,主查询中的CASE语句可以更清晰。

SELECT comp.id, comp.shortname, comp.description,
       (sum(CASE WHEN crs.grade = 'Pass' THEN 1 WHEN crs.grade = 'Fail' THEN -1 ELSE 0 END) >= comp_l.competency_break_level) AS reached_limit
FROM competencies comp
JOIN competency_levels comp_l USING (competency_group)
LEFT JOIN (
  SELECT competency_id, review_status_id
  FROM call_competency
  JOIN users ON id = user_id
  WHERE email = _studentemail
) call_c ON call_c.competency_id = comp.id
LEFT JOIN competency_review_status crs ON crs.id = call_c.review_status_id
GROUP BY comp.id, comp.shortname, comp.description
ORDER BY comp.id;