从不同的表中添加数据 - mysql

时间:2017-10-05 10:13:06

标签: mysql

我有以下表Job descriptionCandidate 每个职位描述可以与n个候选人相关。候选人来自不同的来源(a,b,c d) - candidate.source

我想要一个查询来列出JD ID,每个JD的每个源的候选计数,如下所示:

JD id | candidate name | count of candidates - source a | count of candidates - source b | count of candidates - source | c..............

3 个答案:

答案 0 :(得分:2)

尝试将查询用作模板:

select 
JobDescriptionName, 
SUM(ACount) CountOfCandidatesOfA ,  
SUM(BCount) CountOfCandidatesOfB, 
SUM(CCount) CountOfCandidatesOfC ,  
SUM(DCount) CountOfCandidatesOfD 
from 
 ( select JobDescriptionID, (CASE WHEN Source = 'a' THEN 1 ELSE 0 END) AS ACount, 
            (CASE WHEN Source = 'b' THEN 1 ELSE 0 END) AS BCount, 
            (CASE WHEN Source = 'c' THEN 1 ELSE 0 END) AS CCount, 
            (CASE WHEN Source = 'd' THEN 1 ELSE 0 END) AS DCount 
            from Candidate) AS DerivedCandidate

 inner join JobDescription ON JobDescription.JobDescriptionID = DerivedCandidate.JobDescriptionID group by JobDescriptionID;

答案 1 :(得分:1)

我知道已经有一个已经接受的答案,但是为了更多地了解SQL,这里有一种替代方法可以直接在初始选择中应用case而不使用子选择:

Select 
  jd.id,
  jd.name, 
  sum(case when c.source = 'a' then 1 else 0 end) as sourceA,
  sum(case when c.source = 'b' then 1 else 0 end) as sourceB,
  sum(case when c.source = 'c' then 1 else 0 end) as sourceC,
  sum(case when c.source = 'd' then 1 else 0 end) as sourceD
from JobDescription as jd
join Candidate as c on c.jobId = jd.id
group by jd.id, jd.name

SQL Fiddle Demo

答案 2 :(得分:0)

SELECT JD id, COUNT(Candidate), source
FROM table1
GROUP BY JD id,source