一段时间内的日期计数

时间:2014-12-05 23:17:30

标签: sql sql-server-2008

我有一个带有员工数据的Table1,如下所示

| empid | department | startdate | enddate | | 1 | D1 | 2014-02-05 | 2014-06-18 | | 1 | D3 | 2013-08-29 | 2014-02-05 | | 2 | D3 | 2014-05-07 | 2014-06-18 | | 2 | D4 | 2013-08-29 | 2014-05-06 | | 2 | D3 | 2014-06-19 | 2014-12-01 |

我有另一张Table2表,他们的缺席数据

empid department absentceDate 1 D3 2013-09-24 1 D3 2013-09-30 1 D3 2013-10-25 1 D1 2014-02-06
1 D1 2014-02-08 2 D3 2013-08-30 2 D3 2013-09-30 2 D3 2013-10-30 2 D3 2014-11-11 2 D4 2014-05-10

我加入了两个表格,根据以下代码使用empid查找员工的缺席日期计数:

SELECT   T1.empid as empid,
                    T1.department as department,
                    COUNT(absencedate) AS NumDaysAbsent ,
                    startdate, enddate,

           FROM     Table1 T1
                    JOIN Table2 T2 SE ON sa.empid = se.empid
           GROUP BY T1.empid ,
                    T1.department
                    startdate, enddate

我的结果如下

empid department NumDaysAbsent startdat enddate 1 D1 5 2014-02-05 2014-06-18 1 D3 5 2013-08-29 2014-02-05 2 D3 5 2014-05-07 2014-06-18 2 D3 5 2014-06-19 2014-12-01 2 D4 5 2013-08-29 2014-05-06

相反,我想按部门对numberofAbsences进行分组,并将它们作为

进行透明处理

empid department NumDaysAbsent startdate enddate 1 D1 2 2014-02-05 2014-06-18 1 D3 3 2013-08-29 2014-02-05 2 D3 3 2014-05-07 2014-06-18 2 D3 1 2014-06-19 2014-12-01 2 D4 1 2013-08-29 2014-05-06

我该怎么办?我一直试图弄清楚如何实现这一目标。我如何在startdate和enddate中对它们进行分组,并且在该部门中对他们的期间缺勤数量进行分析? 有什么投入?我试图在SQL Server中执行此操作

1 个答案:

答案 0 :(得分:0)

我认为你需要更多的加入条件,包括部门和日期。我最好的猜测是:

SELECT   T1.empid as empid, T1.department as department,
         COUNT(absencedate) AS NumDaysAbsent ,
         startdate, enddate,
FROM     Table1 T1 JOIN
         Table2 T2
         ON t1.empid = t2.empid AND t1.department = t2.department and
            t2.absencedate between t1.startdate and t1.enddate
GROUP BY T1.empid, T1.department, startdate, enddate;