我正在做一份报告,以显示我们每周从学校获得的申请人数量。我们在15所不同的学校招聘。我目前的疑问是这样的。问题是,如果学校没有获得申请人,那么他们就不会出现在报告中。即使没有申请人,我怎么能让学校出现?
SELECT
weekofyear(tbl_job_applications.ja_date) AS 'Week #',
tbl_universities.univ_name,
Count(tbl_job_applications.ja_date) AS 'Applicants'
FROM
tbl_job_applications
Inner JOIN
tbl_universities ON tbl_job_applications.univ_id = tbl_universities.univ_id
Inner JOIN
tbl_positions ON tbl_job_applications.pos_id = tbl_positions.pos_id
where year(tbl_job_applications.ja_date) = 2014
Group by tbl_universities.univ_name , weekofyear(tbl_job_applications.ja_date)
Order by weekofyear(tbl_job_applications.ja_date) DESC , tbl_universities.univ_name ASC;
答案 0 :(得分:0)
使用LEFT JOIN
或RIGHT JOIN
。 INNER JOIN
排除了非加入值,您的WHERE
条件也需要更改为不排除没有ja_date
值的记录:
SELECT weekofyear(a.ja_date) AS 'Week #'
, u.univ_name
, COUNT(a.ja_date) AS 'Applicants'
FROM tbl_universities u
LEFT JOIN tbl_job_applications a
ON a.univ_id = u.univ_id
LEFT JOIN tbl_positions p
ON a.pos_id = p.pos_id
WHERE YEAR(a.ja_date) = 2014 OR a.ja_date IS NULL
GROUP BY u.univ_name
, weekofyear(a.ja_date)
ORDER BY weekofyear(a.ja_date) DESC
, u.univ_name ASC;
注意,这会返回所有univ_name
值,但它不会每周返回univ_name
个值,如果这是您需要的后的值要创建具有所有周和univ_name组合的驱动程序,最简单的方法是使用子查询中的CROSS JOIN
(在此示例中,它仅限于至少有一个学校的申请人数周,如果你希望所有几周都不得不以不同的方式进行设置:
SELECT sub.*,COUNT(a.ja_date)
FROM (SELECT DISTINCT
weekofyear(a.ja_date) AS week_
,u.univ_name
,u.univ_id
FROM tbl_job_applications a
CROSS JOIN tbl_universities u
) as sub
LEFT JOIN tbl_job_applications a
ON a.univ_id = sub.univ_id
AND weekofyear(a.ja_date) = sub.week_
LEFT JOIN tbl_positions p
ON a.pos_id = p.pos_id
GROUP BY sub.univ_name
,sub.week_
ORDER BY week_
,sub.univ_name
两者的演示:SQL Fiddle
答案 1 :(得分:0)
更改查询,以便首先列出大学并使用外部联接:
FROM tbl_universities
LEFT JOIN tbl_job_applications
ON tbl_job_applications.univ_id = tbl_universities.univ_id
INNER JOIN tbl_positions
ON tbl_job_applications.pos_id = tbl_positions.pos_id