如何确定员工出勤数据的两个不同的聚合日期?

时间:2014-06-18 08:10:55

标签: sql sql-server

我需要帮助来实施员工出勤表。目前正在招聘员工,即

查询:

SELECT c.First_name + c.Middle_name + c.last_name AS employeename,
       b.Device_Person_id,a.Dept_Id,Date1, 
       CASE WHEN b.Device_Person_id IS NOT NULL 
            THEN 'P' 
            ELSE 'A' END AS status
FROM Emp_setting a 
  LEFT OUTER JOIN (SELECT Device_Person_id, MAX(logDateTime) AS Date1 
                 FROM tempDeviceLogs 
                 GROUP BY Device_Person_id) b
    ON a.personal_id = b.Device_Person_id 
  LEFT OUTER JOIN persons_profile c 
    ON c.pesonal_id=a.personal_id

结果:

employeename      Device_person_id      dept_id      date1                status

MEHABOOB             NULL                 4         NULL                    A
UDAY                 NULL                 26    NULL                        A  
SHANKRAYYA           NULL                 10    NULL                        A
BASAVARAJ            NULL                 24    NULL                        A
BHIMAPPA              5                   10       2014-05-23 14:14:00.000      P

即。 Employeename BHIMAPPA出现在2014-05-23

现在我想要出席2014-05-23的员工名单。

请帮帮忙?

2 个答案:

答案 0 :(得分:0)

假设logDateTime表示员工的存在,并且假设当前派生表返回此字段的MAX()(可能是最后一次检测到员工),则需要另一个联接要进行过滤的tempDeviceLogs表。您可以使用INNER JOIN同时进行过滤,即:

...
INNER JOIN (SELECT Device_Person_id 
            FROM tempDeviceLogs 
            WHERE logDateTime >= '2014-05-23' and logDateTime < '2014-05-24') x
   ON x.Device_Person_id = a.personal_id

修改
鉴于您想要SELECT日期,我假设您要对其进行参数化/将其用于范围。关于你的SqlServer版本是&gt; = 2008的另一个假设,将DateTime投射到Date并按其分组:

SELECT c.First_name + c.Middle_name + c.last_name AS employeename,
      b.Device_Person_id,a.Dept_Id, Date1 as DateTimeLastSeen, 
      x.logDate As DatePresent,
      CASE WHEN b.Device_Person_id IS NOT NULL THEN 'P' ELSE 'A' END AS status
FROM Emp_setting a 
  LEFT OUTER JOIN (SELECT Device_Person_id, MAX(logDateTime) AS Date1 
                   FROM tempDeviceLogs 
                   GROUP BY Device_Person_id) b 
     ON a.personal_id = b.Device_Person_id 
  LEFT OUTER JOIN persons_profile c 
     ON c.pesonal_id=a.personal_id
  INNER JOIN (SELECT Device_Person_id, CAST(logDateTime AS DATE) as logDate
              FROM tempDeviceLogs 
              GROUP BY Device_Person_id, CAST(logDateTime AS DATE)) x
  ON x.Device_Person_id = a.personal_id
WHERE 
     logDate BETWEEN '2014-05-01' AND '2014-05-23';

这也可以通过DISTINCT完成。如果您有早期版本的SqlServer,请使用hack like this获取DateTime的日期部分(在select +组中)

答案 1 :(得分:0)

创建一个变量来保存您要查找的日期。

DECLARE @cutOffDate DATE
SET @cutOffDate = '23-05-2014'

然后添加到您的陈述的末尾

Where Date1 = @cutOffDate