获得两个表的连接的明确计数

时间:2017-11-13 07:20:55

标签: sql-server

我有2个表,其中第一个表的主键用作第二个表的外键。在第一个表中,主键具有唯一值,但在第二个表中作为外键,它也具有重复值。现在我想同时从两个表中计数并使用左连接。 我尝试过以下查询: -

 select distinct count(c.joined) as joined,
    count(t.JobReqID),t.Country from txrecruitment as t 
    left join CandidateDetails as c on t.JobReqID=c.Jobreqid 
    where t.status='open'
    group by t.Country

count(t.JobReqID)的计数值没有给出我想要的不同JobReqId的计数。 count的结果是计算我要删除的第二个表的多个实例。 应该采取什么样的正确方法。欢迎任何帮助!!

2 个答案:

答案 0 :(得分:1)

因为我们的distinct没有放在正确的位置。在计数内使用不同。

 select count(distinct  c.joined) as joined,
    count(DISTINCT t.JobReqID),t.Country from txrecruitment as t 
    left join CandidateDetails as c on t.JobReqID=c.Jobreqid 
    where t.status='open'
    group by t.Country

答案 1 :(得分:1)

使用DISTINCT计算 JobReqID ,如下所示:

select count(c.joined) as joined, count(distinct t.JobReqID), t.Country 
from txrecruitment as t 
left join CandidateDetails as c on t.JobReqID=c.Jobreqid 
where t.status='open'
group by t.Country