员工的SQL列表目前正在进行中

时间:2015-11-13 11:52:32

标签: sql sql-server tsql

我试图获取目前进入我们工厂的员工名单。 时钟事务更新时钟表: ' dayreviewinoutflag = 0'用于计时IN和' dayreviewinoutflag = 1'用于计时OUT 我想回顾过去72小时,以便为员工获取最新的IN时钟 他们的最后一次计时不是OUT时钟。

我觉得下面的查询几乎就在那里,但是......

$person = new Person('Foo', 'Bar');
echo $person;
echo '<hr />';
PersonRender::$chosenToStringMethod = PersonRender::PRINT_SURNAME_FIRST_UPPERCASE;
echo $person;

此时我收到有关聚合函数或GROUP BY的错误,但是如果我尝试添加&#39; dayreviewinoutflag&#39;进入GROUP它没有结果。

任何反馈都将不胜感激。

下面的表数据应导致EMPLOYEECODE 11307未在结果列表中返回

SELECT cc.* 
FROM   clocking cc 
       INNER JOIN (SELECT employeecode, 
                          Max(clockingdatetimeunrounded) AS MaxDateTime, 
                          CASE 
                            WHEN clocking.dayreviewinoutflag = 0 THEN Max( 
                            clockingdatetimeunrounded) 
                            ELSE NULL 
                          END                            AS InDateTime, 
                          CASE 
                            WHEN clocking.dayreviewinoutflag = 1 THEN Max( 
                            clockingdatetimeunrounded) 
                            ELSE NULL 
                          END                            AS OutDateTime 
                   FROM   clocking 
                   WHERE  clockingdatetimeunrounded >= 
                          Dateadd(hour, -72, Getdate()) 
                   GROUP  BY employeecode) groupedcc 
               ON cc.employeecode = groupedcc.employeecode 
                  AND cc.clockingdatetimeunrounded = groupedcc.maxdatetime 
                  AND groupedcc.indatetime > groupedcc.outdatetime 

1 个答案:

答案 0 :(得分:3)

您最初的问题是您在查询中使用clocking.dayreviewinoutflag,因此它必须包含在您的GROUP BY子句中。

您编写的查询无法达到您的目标,您的内部选择正在尝试同时获取员工的最后进/出日期时间。您需要将这些查询拆分为单独的查询,然后将它们连接起来进行比较:

WITH cte_LastClockIn AS
(
    SELECT employeecode, 
          Max(clockingdatetimeunrounded) AS InDateTime, 
    FROM   clocking 
    WHERE  clockingdatetimeunrounded >= 
          Dateadd(hour, -72, Getdate())
    AND clocking.dayreviewinoutflag = 0
    GROUP  BY employeecode
)

,cte_LastClockOut AS
(
    SELECT employeecode, 
          Max(clockingdatetimeunrounded) AS OutDateTime, 
    FROM   clocking 
    WHERE  clockingdatetimeunrounded >= 
          Dateadd(hour, -72, Getdate())
    AND clocking.dayreviewinoutflag = 1
    GROUP  BY employeecode
)


SELECT 
    cc.* 
FROM clocking cc 

INNER JOIN cte_LastClockIn lci
ON cc.employeecode = lci.employeecode
AND cc.clockingdatetimeunrounded = lci.InDateTime

INNER JOIN cte_LastClockOut lco
ON cc.employeecode = lco.employeecode

WHERE lci.InDateTime > lco.OutDateTime