员工表列在下面......
Name DOJ DOL
............ ............... ............
Ram 2014-01-12 2014-02-12
Kiran 2014-02-05 2014-07-05
Jhon 2014-01-25 2014-10-01
预期输出是......
Month Joining_count Leaving_count
........... ................ .................
Jan-2014 2 0
Feb-2014 1 1
. . .
. . .
. . .
我尝试使用下面的Mysql Query但我无法获得预期的输出 请帮帮我
SELECT monthname(current_date) as month,
count( `DATE_OF_JOINING`) as 'Joining_count' ,
count( `DATE_OF_LEAVING`) as 'leaving_count' ,
group by year(`DATE_OF_JOINING`),month('DATE_OF_JOINING`),
year(`DATE_OF_LEAVING),month(`DATE_OF_LEAVING)
答案 0 :(得分:1)
您正在对同一数据执行两种不同的聚合 - 因此您需要两个汇总查询join
。
不幸的是,mysql没有一个完整的外部联接,因此处理有人离开但没有人加入的几个月以及几个月没有人加入的人都有点麻烦。我用三个连接解决了这个问题 - 一个查询获取所有可能的日期,另一个查询用于每个聚合,尽管there are other ways。
SELECT my_table.d, COALESCE(join_count, 0), COALESCE(leave_count, 0)
FROM (SELECT DISTINCT DATE_FORMAT(doj, '%b-%y') AS d
FROM my_table
UNION
SELECT DISTINCT DATE_FORMAT(dol, '%b-%y')
FROM my_table) dates
LEFT JOIN (SELECT DATE_FORMAT(doj, '%b-%y') d, COUNT(*) AS join_count
FROM my_table
GROUP BY DATE_FORMAT(doj, '%b-%y')
) joins ON dates.d = joins.d
LEFT JOIN (SELECT DATE_FORMAT(dol, '%b-%y') d, COUNT(*) AS leave_count
FROM my_table
GROUP BY DATE_FORMAT(dol, '%b-%y')
) leaves ON dates.d = leaves.d
答案 1 :(得分:0)
基本上,您需要两个查询,一个用于分组加入日期,另一个用于离开日期。您可以使用UNION ALL
合并两个结果,并将合并后的结果视为新表,然后选择(和SUM
)值。
SELECT
s.month,
SUM(s.Joining_count) AS Joining_count,
SUM(s.Leaving_count) AS Leaving_count
FROM
(
SELECT
DATE_FORMAT(doj, '%b-%y') as `month`,
COUNT(ej.doj) as 'Joining_count',
0 AS 'Leaving_count'
FROM employee ej
GROUP BY `month`
UNION ALL
SELECT
DATE_FORMAT(dol, '%b-%y') as `month`,
0 as 'Joining_count',
COUNT(el.dol) as 'Leaving_count'
FROM employee el
GROUP BY `month`
) s
GROUP BY s.`month`;
输出
month Joining_count Leaving_count
---------------------------------------------
Feb-2014 1 1
Jan-2014 2 0
Jul-2014 0 1
Oct-2014 0 1