我在MySQL中有两个表:
emp_detail
----------------------------------------------------------------------
emp_number(int)| emp_id(int) | emp_name(varchar) | joined_date (date)
----------------------------------------------------------------------
和
----------------------------------------------------------------------
emp_termination
----------------------------------------------------------------------
emp_number(int)foreign key| termination_reason(varchar) | termination_date (date)
----------------------------------------------------------------------
我想要每年的月度记录,包括每个月离开或加入公司的员工人数:
-----------------------
month | joined | left
-----------------------
答案 0 :(得分:1)
使用UNION ALL
加入并将员工分成两行,然后按月合并以离开并加入一行。
SELECT year, month, SUM(joined), SUM(left)
FROM
(SELECT YEAR(ed.joined_date) AS year, MONTH(ed.joined_date) AS month, COUNT(MONTH(ed.joined_date)) AS joined, 0 AS left
FROM emp_detail AS ed
GROUP BY YEAR(ed.joined_date), MONTH(ed.joined_date)
UNION ALL
SELECT YEAR(ed.termination_date) AS year, MONTH(ed.termination_date) AS month, COUNT(MONTH(et.termination_date)) AS left, 0 AS joined
FROM emp_termination AS et
GROUP BY YEAR(ed.termination_date), MONTH(et.termination_date)) AS my_table
GROUP BY year, month
答案 1 :(得分:0)
试试这个..
select table1.monthname, table1.Joined, table2.LeftCop from
(
select year(joined_date) year
, MONTHNAME(STR_TO_DATE( month(joined_date) , '%m')) as monthname
,count(*) as Joined
,0 as LeftCop
from emp_detail
group by month(joined_date) , year(joined_date)
) Table1
join
(
select year(termination_date) year
, MONTHNAME(STR_TO_DATE( month(termination_date) , '%m')) as monthname
,0 as Joined
,count(*) as LeftCop
from emp_termination
group by month(termination_date) , year(termination_date)
) table2
on table1.year = table2.year and table1.monthname = table2.monthname