动态设置一天的开始和结束时间

时间:2019-01-04 05:38:59

标签: sql-server

我有这张表,用于存储TimeIn和Time Out of Employee。 当我获得总时数时,任何员工在某天都工作过,这是明智的选择。但是在外部组织中,问题是要考虑从凌晨6点到凌晨5:59(第二天)的一天。

这是我的表格和示例数据。

CREATE TABLE [dbo].[Attendance]
(
    [Employee] [varchar](50) NULL,
    [TimeIn] [datetime] NULL,
    [TimeOut] [datetime] NULL
) ON [PRIMARY]
GO

INSERT [dbo].[Attendance] ([Employee], [TimeIn], [TimeOut]) VALUES (N'Lewis', CAST(N'2018-12-01 06:30:00.000' AS DateTime), CAST(N'2018-12-01 18:22:00.000' AS DateTime))
GO
INSERT [dbo].[Attendance] ([Employee], [TimeIn], [TimeOut]) VALUES (N'Lewis', CAST(N'2018-12-01 20:12:00.000' AS DateTime), CAST(N'2018-12-01 23:50:00.000' AS DateTime))
GO
INSERT [dbo].[Attendance] ([Employee], [TimeIn], [TimeOut]) VALUES (N'Lewis', CAST(N'2018-12-02 00:12:00.000' AS DateTime), CAST(N'2018-12-02 04:50:00.000' AS DateTime))
GO
INSERT [dbo].[Attendance] ([Employee], [TimeIn], [TimeOut]) VALUES (N'Lewis', CAST(N'2018-12-02 07:21:00.000' AS DateTime), CAST(N'2018-12-02 19:54:00.000' AS DateTime))
GO

这是我正在执行的查询和查询的输出。

SELECT Employee, CAST(COALESCE(TimeIn, TimeOut) AS DATE) DATE, DATEDIFF(HOUR, MIN(TimeIn), MAX(TimeOut)) [Hours Worked]
FROM [dbo].[Attendance]
GROUP BY Employee, CAST(COALESCE(TimeIn, TimeOut) AS DATE)

输出:

Employee          DATE         Hours Worked
----------------- ----------   ------------
Lewis             2018-12-01   17
Lewis             2018-12-02   19

我想要得到的工作时间是从第二天的凌晨6点到5:59。因此,预期的输出如下:

Employee          DATE         Hours Worked
----------------- ----------   ------------
Lewis             2018-12-01   22:20
Lewis             2018-12-02   12:33

希望这是可能的。

1 个答案:

答案 0 :(得分:3)

您可能应该有一个日历表,其中包含要显示在报告中的所有日期。如果没有这种情况,我们可以假设所有日期都被时间覆盖,并且可以按时间分组,并提前6个小时。这里的窍门是,我们可以将所有时间向后移动6小时,以使所有内容与通常的24小时制保持一致。这样的事情应该起作用:

SELECT
    Employee,
    CONVERT(date, DATEADD(HOUR, -6, TimeIn)) AS DATE,
    CONVERT(VARCHAR(10), DATEDIFF(HOUR, MIN(TimeIn), MAX(TimeOut))) + ':' +
        CONVERT(VARCHAR(10), DATEDIFF(MINUTE, MIN(TimeIn), MAX(TimeOut)) % 60) AS [Hours Worked]
FROM Attendance
GROUP BY
    Employee,
    CONVERT(date, DATEADD(HOUR, -6, TimeIn));

enter image description here

Demo