繁体   English   中英

SQL的最小最大日期

[英]SQL for Min Max Dates

Start      End
10:01      10:12     (A)
10:03      10:06     (A)
10:05      10:25     (C)
10:14      10:42     (D)
10:32      10:36     (E)

当我查询A时,我需要

Start      End
10:12      10:03     (A)

什么是SQL查询PLS。 谢谢


伙计们,谢谢您的答复。 我的目标是计算时间表。 员工会突击而出。 我将这些记录存储在一张表中。 那张桌子有时间,还有一个地方供打孔或打孔。 员工可能会出于午餐或其他原因外出,并要求外出打孔。我需要扣除这些时间并获得工作时间。 我的表如下所示:

    PunchTime  EmpCode    IsInpunch
    10:01 AM   (A)        T
    12:03 PM   (A)        F            (this isoutpunch) 
    01:05 PM   (A)        T
    07:14 PM   (A)        F
    10:32 AM   (B)        T

因为(A)的时间是总时间7.14-10.01,但他不在12.03到01.05之间,所以我需要扣除午餐时间并获得总时间。 如何在查询中执行此操作

SELECT max(start), min(end) FROM table WHERE column='A';

如果您要寻找总时间,可以这样做。

DECLARE @testData table (
Punchtime datetime, empcode char(3), isInPunch char(1))


INSERT INTO @testData
Values
('10:01 AM ',  '(A)', 'T'),
('12:03 PM',   '(A)', 'F'),
('01:05 PM',   '(A)', 'T'),
('07:14 PM',   '(A)', 'F'),
('10:32 AM',   '(B)', 'T')

;WITH CTE as(
SELECT 
    DENSE_RANK() over (Partition by empcode , isInPunch  Order by punchTime) id,
    Punchtime,
    empcode,
    isInPunch

FROM 
    @testData
WHERE 
         empcode = '(A)'
    )
SELECT
     Cast(cast(sum(
        cast(outTime.punchTime as float) - cast(inTime.punchTime as float)
        )as datetime) as time)
FROM 
     CTE inTime
     INNER JOIN CTE outTime
     ON inTime.empcode = outTime.empcode
         AND inTime.id = outTime.id
        AND inTime.isInPunch = 'T'
        and outTime.isInPunch = 'F'

该查询在Punch ='F'之后找到Punch ='T'的First PunchTime(非工作时间)。 然后,您可以简单地计算datediff和类似的东西。

SELECT  EmpCode,
        PunchTime StartTime,
        (SELECT TOP 1 PunchTime from Table1 
         where IsInpunch = 'T' and EmpCode=T.EmpCode and PunchTime>T.PunchTime
         order by PunchTime) EndTime
FROM    Table1 T
WHERE   IsInpunch = 'F'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM