2014-10-09 91 views
-1

我在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

你可以添加樣本數據嗎? – Jens 2014-10-09 05:58:08

+0

請大家幫忙,包括你自己,並請閱讀http://meta.stackexchange.com/questions/10647/how-do-i-write-a-good-title謝謝! – reto 2014-10-09 05:59:50

+0

是的牛仔褲像int值將像1,2,3 ...,varchar將是簡單的字符串日期格式爲'01 -02-2014'我想要加入和離開(終止)在幾個月告訴我你是否需要進一步的信息和謝謝回覆 – Swapnil1988 2014-10-09 06:06:16

回答

1

使用UNION ALL加入並離開兩行員工,然後按月組合t o離開並加入一行。

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 
+0

@swapnil:請讓我知道是否有幫助 – 2014-10-09 06:28:29

+0

雅謝謝你的作品... – Swapnil1988 2014-10-09 06:30:38

+0

酷,請讓我知道如果有些事不清楚。 – 2014-10-09 06:31:41

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