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

问题描述:

我想根据多个表中的ID显示计数。对于两个表是工作正常,但对于三桌它不显示数据如何使用连接查询从多个表中获取计数(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; 
+0

没有结果意味着两件事中的一件事:1 Where子句条件是排除所有数据。正在进行连接,并且未找到加入标准上的匹配项。我们没有足够的信息来了解问题所在。 where子句中的区分大小写?消除where子句,你会得到计数/结果吗?如果是这样,上面两块和修剪? 'TRIM(UPPER(cis.interview_status))= UPPER('Interview Scheduled')'对于连接:你确定你有一个req_ID存在于所有3个表中吗?我们不知道两个表的工作原理。这将有助于隔离问题。 – xQbert

+0

req_id在不同的表中有所不同,但我想显示所有req_id,如果值不匹配其他表中的值,则返回null –

+0

然后,您需要或许需要在两个表上使用LEFT Join,以便如果req_ID不会不存在于两个表中的一个中,它仍将被显示。此外,如果你的这些表有1:M relatioships,那么你的计数将会被夸大,所以你可能需要使用分区计数... – xQbert

  1. 改为左联接柜面值好好尝试一下存在在表
  2. 改变计数使用一个窗口功能,因此计数没有人为夸大的加入
  3. 移动where子句的加入标准作为一个LEFT JOIN,那就否定了空值,使其像一个内部联接操作。

..MAYBE ...

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; 
+0

是的,它解决了我的问题谢谢 –