我想写一个查询来生成员工的考勤报告。首先,我将告诉您,员工的存在是如何存储在我的数据库中的。
我有下列表格。
Employee Table with Columns
emp_id emp_Name Joining_Date
1 john 11-01-2012
2 Scott 12-01-2012
Holiday Table
Holiday_Name Date
Chrismas 25-12-2012
Dushera 08-03-2012
Independance Day 15-08-2012
Leave Table
Subject from_Date to_Date Emp_Id status
PL 02-01-2012 04-01-2012 1 Approved
CL 11-01-2012 12-01-2012 2 Declined
Doctor Table
Subject Call_Date call_Done_By(emp_id)
Call 15-01-2012 1
CA 21-02-2012 2
Chemist Table
Subject Call_Date call_Done_By(emp_id)
Chemist 1-02-2012 2
Texo 21-03-2012 1
如果员工被探视为医生或化学家,则该特定日期将与员工id一起存储在该特定医生或化学家表中
现在人员将选择年和月,他应该能够得到以下格式的出勤报告
示例:假设用户选择year作为“2011”,选择month作为“Dec”,那么输出应该是
Employee year Month 1 2 3 4 5 6 7....
John 2011 Nov Y Y Y Y Y L S....
Scott 2011 Nov Y Y L M Y L S
在输出1,2,3。。。。是一个月的0-30天,我们可以用“case”来写
考虑员工当天是否在场,显示其“是”或“其他”的状态
如果他去找任何顾客,比如医生、药剂师,那就换成“S”。
那么我应该如何编写一个查询来实现这个输出呢??
任何建议对我都有帮助。。。。
最佳答案
这是一条很长的路,应该如预期的那样工作:
SELECT
Employee.emp_Name,
'2011' AS `Year`,
'Dec' AS `Month`,
CASE (
IF(
DATE('1-12-2011') < DATE(Employee.Joining_Date)),
'0' --Not joined yet
IF (
(SELECT COUNT(*) FROM Holiday WHERE DATE('1-12-2011') = DATE(Holiday.date)) = 1,
'1', --National Holiday
IF (
(SELECT COUNT(*) FROM Leave WHERE DATE('1-12-2011') > DATE(Leave.to_Date) AND DATE('1-12-2011') < DATE(Leave.from_Date) AND Leave.Emp_Id = Employee.emp_id) = 1,
'2', --On Leave
IF(
(SELECT COUNT(*) FROM Doctor WHERE DATE('1-12-2011') > DATE(Doctor.Call_Date) AND Doctor.call_Done_By = Employee.emp_id) = 1 OR
(SELECT COUNT(*) FROM Chemist WHERE DATE('1-12-2011') > DATE(Chemist.Call_Date) AND Chemist.call_Done_By = Employee.emp_id) = 1,
'3' --Visit Doctor or Chemist
'4' --Employee was at work
)
)
)
)
)
WHEN 0 THEN 'N/A' --Not joined yet
WHEN 1 THEN 'L' --National Holiday
WHEN 2 THEN 'L' --On Leave
WHEN 3 THEN 'S' --Visit Doctor or Chemist
ELSE 'Y' --Employee was at work
END AS `1`, --first day of month
... AS `2`, --repeat for second day of the month till max day of current month replace '1-12-2011' with each different day of month
...
... AS `30`
FROM
Employee
我的建议是为每个员工创建一个执行if语句的视图,这样代码就更容易维护了。请记住,这是伪代码,可能需要一些更改才能运行。
希望这有帮助。