CTE缺失记录

时间:2016-02-26 17:30:22

标签: sql postgresql common-table-expression

下面列出的第一个查询会返回与在特定时间段内完成的招聘相关的一些后勤数据。该查询返回478条记录。

SELECT c.candidate_id AS candidate_id
,o.name 
,j.name AS job_title
,c.applied_from
,job_id AS job_id 
,cjs.score AS smart_rank_score
,cjs.is_completed AS smartrank_completion_status
,c.hired_at
FROM candidate_jobs c
LEFT JOIN organizations o ON o.id = c.organization_id
LEFT JOIN candidate_job_surveys cjs ON cjs.candidate_job_id = c.id
LEFT JOIN jobs j ON j.id = c.job_id
WHERE o.name LIKE ANY ('{"%Tutor Doctor%"}')
AND c.hired_at :: date BETWEEN '2015-01-01' AND '2016-02-22'
ORDER BY 8 DESC

但是,当我尝试添加一个CTE(见下文),显示每个雇员的最终"雇用后检查分数",查询只返回236条记录。理想情况下,我希望查询能够为每个最初的478个雇佣记录返回分数或空值。

WITH final_post_hire_score (candidate_id, final_score) AS
(SELECT c.candidate_id
  ,p.score 
  FROM post_hire_followup_reviews p 
  LEFT JOIN candidate_jobs c ON c.id = p.candidate_job_id 
  WHERE p.check_in_number = 3)

SELECT c.candidate_id AS candidate_id
,o.name 
,j.name AS job_title
,c.applied_from
,job_id AS job_id 
,cjs.score AS smart_rank_score
,cjs.is_completed AS smartrank_completion_status
,c.hired_at
,final_score
FROM final_post_hire_score f
LEFT JOIN candidate_jobs c ON c.candidate_id = f.candidate_id
LEFT JOIN organizations o ON o.id = c.organization_id
LEFT JOIN candidate_job_surveys cjs ON cjs.candidate_job_id = c.id
LEFT JOIN jobs j ON j.id = c.job_id
WHERE o.name LIKE ANY ('{"%Tutor Doctor%"}')
AND c.hired_at :: date BETWEEN '2015-01-01' AND '2016-02-22'
ORDER BY 8 DESC

2 个答案:

答案 0 :(得分:0)

缺少记录取决于过滤器,将过滤器移至ON条件,否则您的LEFT OUTER JOIN将隐式转换为INNER JOIN

当您使用LEFT OUTER JOIN 右表时,过滤器应出现在ON条件中,否则非匹配记录的NULL值将会获得过滤

WITH final_post_hire_score (candidate_id, final_score)
     AS (SELECT c.candidate_id,
                p.score
         FROM   post_hire_followup_reviews p
                LEFT JOIN candidate_jobs c
                       ON c.id = p.candidate_job_id
         WHERE  p.check_in_number = 3)
SELECT c.candidate_id   AS candidate_id,
       o.NAME,
       j.NAME           AS job_title,
       c.applied_from,
       job_id           AS job_id,
       cjs.score        AS smart_rank_score,
       cjs.is_completed AS smartrank_completion_status,
       c.hired_at,
       final_score
FROM   final_post_hire_score f
       LEFT JOIN candidate_jobs c
              ON c.candidate_id = f.candidate_id
             AND c.hired_at :: date BETWEEN '2015-01-01' AND '2016-02-22'
       LEFT JOIN organizations o
              ON o.id = c.organization_id
             AND o.NAME LIKE ANY ( '{"%Tutor Doctor%"}' )
       LEFT JOIN candidate_job_surveys cjs
              ON cjs.candidate_job_id = c.id
       LEFT JOIN jobs j
              ON j.id = c.job_id
ORDER  BY 8 DESC 

答案 1 :(得分:0)

我认为还有额外的

WHERE p.check_in_number = 3

不是其他任何地方。