如何使用连接查询从多个表中获取计数(id)

时间:2016-12-15 19:05:35

标签: oracle oracle11g

我想根据多个表中的id显示计数。对于两个表,它工作正常,但对于三个表,它不显示数据

这是我对三个表无法正常工作的查询

select r.req_id
     , r.no_of_positions
     , count(j.cand_id) as no_of_closure
     , count(cis.cand_id) 
from requirement r 
join joined_candidates j 
  on r.req_id=j.req_id
join candidate_interview_schedule cis 
  on cis.req_id=r.req_id 
where cis.interview_status='Interview Scheduled' 
group by r.req_id, r.no_of_positions;

1 个答案:

答案 0 :(得分:0)

  1. 更改为左连接,表格中存在值不存在
  2. 更改计数以使用窗口功能,因此连接不会人为地夸大计数
  3. 将where子句移动到连接条件,就像在左连接上一样,它会否定空值,使其像内连接一样运行。
  4. ..也许...

    SELECt r.req_id
         , r.no_of_positions
         , count(j.cand_id) over (partition by J.cand_ID) as no_of_closure
         , count(cis.cand_id) over (partition by cis.cand_id) as no_of_CIS_CNT
    FROM  requirement r 
    LEFT join joined_candidates j 
      on r.req_id=j.req_id
    LEFT join candidate_interview_schedule cis 
      on cis.req_id=r.req_id 
     and  cis.interview_status='Interview Scheduled' 
    GROUP BY  r.req_id, r.no_of_positions;
    

    或者......(如果我可以假设j.cand_ID和cis.cand_ID是唯一的)也可以消除由于1:M连接引起的人工计数增加

    SELECt r.req_id
         , r.no_of_positions
         , count(distinct j.cand_id) as no_of_closure
         , count(distinct cis.cand_id) as no_of_CIS_CNT
    FROM  requirement r 
    LEFT join joined_candidates j 
      on r.req_id=j.req_id
    LEFT join candidate_interview_schedule cis 
      on cis.req_id=r.req_id 
     and  cis.interview_status='Interview Scheduled' 
    GROUP BY  r.req_id, r.no_of_positions;