我正在尝试执行查询。但它没有像我预期的那样工作。 这是我的疑问:
select mo.year,mo.month,count(emp_id)
from employee em
right outer join months mo on ifnull(em.joining_date,'2010-01-01') < mo.start_date
and ifnull(em.relieving_date,'2050-01-01') > mo.end_date
where em.bill=1 and em.org_id=8
group by mo.month
这是我的月份表:
id start_date end_date month year
'1', '2015-01-01', '2015-01-31', 'January', '2015'
'2', '2015-02-01', '2015-02-28', 'February', '2015'
'3', '2015-03-01', '2015-03-31', 'March', '2015'
'4', '2015-04-01', '2015-04-30', 'April', '2015'
'5', '2015-05-01', '2015-05-31', 'May', '2015'
'6', '2015-06-01', '2015-06-30', 'June', '2015'
'7', '2015-07-01', '2015-07-31', 'July', '2015'
'8', '2015-08-01', '2015-08-31', 'August', '2015'
'9', '2015-09-01', '2015-09-30', 'September', '2015'
'10', '2015-10-01', '2015-10-31', 'October', '2015'
'11', '2015-11-01', '2015-11-30', 'November', '2015'
'12', '2015-12-01', '2015-12-31', 'December', '2015'
这是我的员工表:
id joining_date relieving_date bill org_id emp_id
1, NULL, NULL, 0, 8, 1
2, '2015-02-10', NULL, 1, 8, 2
3, '2015-08-05', '2015-11-31', 1, 8, 3
这是我目前的输出:
year org_id month count(emp_id)
'2015', '8', 'April', '2'
'2015', '8', 'August', '2'
'2015', '8', 'December', '2'
'2016', '8', 'February', '1'
'2016', '8', 'January', '1'
'2015', '8', 'July', '2'
'2015', '8', 'June', '2'
'2015', '8', 'March', '2'
'2015', '8', 'May', '2'
'2015', '8', 'November', '2'
'2015', '8', 'October', '3'
'2015', '8', 'September', '3'
我的预期输出是:
year org_id month count(emp_id)
'2015', '8', 'April', '1'
'2015', '8', 'August', '2'
'2015', '8', 'December', '1'
'2016', '8', 'February', '0'
'2016', '8', 'January', '0'
'2015', '8', 'July', '1'
'2015', '8', 'June', '1'
'2015', '8', 'March', '1'
'2015', '8', 'May', '1'
'2015', '8', 'November', '1'
'2015', '8', 'October', '2'
'2015', '8', 'September', '2'
如果缓解日期不是他们的,则计数会自动增加。
任何帮助!!
答案 0 :(得分:-1)
select mo.year, mo.month, count(emp_id)
from employee em
right outer join months mo
on
ifnull(em.joining_date,'2050-01-01') < mo.start_date
and ifnull(em.relieving_date,'2050-01-01') > mo.end_date
where
em.bill=1 and em.org_id=8
group by mo.month