我有一个表名Emp_mon_day
,其中包括员工目前和缺席详情。
我想要的是
我需要这9名员工,从Emp_mon_day
表中合并到以下查询的每个员工的日期和缺席天数信息
QUERY
SELECT e.comp_mkey,
e.status,
e.resig_date,
dt_of_leave,
e.emp_name,
e.date_of_joining,
e.emp_card_no,
a.pl_days,
pl_days_opening,
a.month1,
a.month2,
a.month3,
a.month4,
a.month5,
a.month6,
a.month7,
a.month8,
a.month9,
a.month10,
a.month11,
a.month12,
a.month1 + a.month2 + a.month3 + a.month4 + a.month5 + a.month6 + a.month7 + a.month8 + a.month9 + +a.month10 + a.month11 + a.month12 AS pl_sum
FROM p_leave_allocation AS a
INNER JOIN
emp_mst AS e
ON a.emp_card_no = e.emp_card_no
WHERE a.year = 2016
AND (datediff(MONTH, e.date_of_joining, CONVERT (DATETIME, getdate(), 103)) >= 6
AND datediff(MONTH, e.date_of_joining, CONVERT (DATETIME, getdate(), 103)) <= 36)
AND (e.resig_date IS NULL
OR (e.dt_of_leave IS NOT NULL
AND e.dt_of_leave >= CONVERT (DATETIME, getdate(), 103)))
AND e.status IN ('A', 'S')
AND e.comp_mkey IN (7, 110)
AND a.Year = 2016;
以上查询为我提供了如下数据
[![图像数据] [1]] [1]
Emp_mon_day
的列详细信息在
[![在此处输入图像说明] [2]] [2]
答案 0 :(得分:1)
您可以尝试以下查询:
SELECT e.comp_mkey, e.status, e.resig_date, dt_of_leave, e.emp_name,
e.date_of_joining, e.emp_card_no, a.pl_days, pl_days_opening, a.month1,
a.month2, a.month3, a.month4, a.month5, a.month6, a.month7, a.month8,
a.month9, a.month10, a.month11, a.month12,
a.month1 + a.month2 + a.month3 + a.month4 + a.month5 + a.month6 + a.month7 + a.month8 + a.month9 + +a.month10 + a.month11 + a.month12 AS pl_sum,
m.[DaysAbsent],m.[DaysPresent]
FROM p_leave_allocation AS a
INNER JOIN
emp_mst AS e
ON a.emp_card_no = e.emp_card_no
INNER JOIN
(
SELECT
comp_mkey,emp_mkey,[month],[year],
SUM(CASE WHEN data ='AB' THEN 1 ELSE 0 END) AS [DaysAbsent],
SUM(CASE WHEN data ='P' THEN 1 ELSE 0 END) AS [DaysPresent]
FROM
(
SELECT comp_mkey,emp_mkey,[month],[year],[Day1],[Day2],[Day3],[Day4],[Day5]
--,...
FROM Emp_mon_day
) source
UNPIVOT
(
data FOR day IN ([Day1],[Day2],[Day3],[Day4],[Day5]) -- dynamic query can generate all days data
)up
GROUP BY comp_mkey, emp_mkey,[month],[year]
) AS m
ON m.comp_mkey=e.Comp_mkey and m.emp_mkey=e.mkey
--- ABOVE CRITERIA NEEDS TO BE CHECKED
WHERE a.year = 2016
AND (datediff(MONTH, e.date_of_joining, CONVERT (DATETIME, getdate(), 103)) >= 6
AND datediff(MONTH, e.date_of_joining, CONVERT (DATETIME, getdate(), 103)) <= 36)
AND (e.resig_date IS NULL
OR (e.dt_of_leave IS NOT NULL
AND e.dt_of_leave >= CONVERT (DATETIME, getdate(), 103)))
AND e.status IN ('A', 'S')
AND e.comp_mkey IN (7, 110)
AND a.Year = 2016;
<强>解释强>
我们在现有查询中添加了另一个INNER JOIN,以获取DaysPresent
和DaysAbsent
的整理数据
为了进一步优化,我建议您直接将以下WHERE
条款应用于source
集
WHERE comp_mkey IN (7, 110) AND Year = 2016;