我现在的情况是,我需要找出一些内部申请在办公室花费的总时间。
我有这样的样本数据:
Id EmployeeId ScanDateTime Status
7 87008 2018-08-02 16:03:00.227 1
8 87008 2018-08-02 16:06:17.277 2
9 87008 2018-08-02 16:10:37.107 3
10 87008 2018-08-02 16:20:17.277 2
11 87008 2018-08-02 16:30:37.107 3
12 87008 2018-08-02 20:06:00.000 4
这里的 Status 有不同的含义:
1-开始
2- 暂停
3- 简历
4-结束
表示员工在 ScanDateTime 状态为 1 时开始工作。他们可以休息(状态 2),然后回来继续工作(状态 3),状态 4 表示他们正在结束工作。
注:工作时间内可能会有多次休息时间。
预期输出:
EmployeeId StartTime EndTime BreakInMins
87008 2018-08-02 16:03:00.227 2018-08-02 20:06:00.000 14
我尝试按照一些示例来计算预期结果集,但没有帮助。
我找不到任何这样的例子,其中类似的例子可用。
任何帮助,将不胜感激。
请尝试这个。当休息仍在进行或会话未完成时,处理多个休息/员工和案例
select
[EmployeeId] = [s].[EmployeeId]
,[StartTime] = [s].[ScanDateTime]
,[EndTime] = [et].[ScanDateTime]
,[BreakInMins] = [b].[BreakInMins]
from
[Scans] as [s] -- here is your table
outer apply
(
select top 1 [ScanDateTime], [Id] from [Scans] where [Id] > [s].[Id] and [EmployeeId] = [s].[EmployeeId] and [Status] = 4 order by [ScanDateTime] asc
) as [et]
outer apply
(
select
[BreakInMins] = sum(isnull([r].[mins], datediff(mi, [sp].[ScanDateTime], getdate())))
from
[Scans] as [sp]
outer apply
(
select top 1 [mins] = datediff(mi, [sp].[ScanDateTime], [ScanDateTime]) from [Scans] where [Id] > [sp].[Id] and [EmployeeId] = [sp].[EmployeeId] and [Status] IN (3, 4) order by [ScanDateTime] asc
) as [r]
where
[sp].[id] > [s].[id] and [sp].[id] < isnull([et].[id], [id] + 1)
and [sp].[EmployeeId] = [s].[EmployeeId]
and [sp].[Status] = 2
) as [b]
where
[Status] = 1;
这是测试友好的脚本:script https://pastebin.com/g58zAqTt
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)