sql - How to insert records as break times in a select in a Stored Procedure -
having table in sql server 2012
, need return break times inserted in right position.
i able use temporary tables if necessary.
break: difference between times, need new record representing gaps.
table:
╔════════════════╦════════════════╦══════════╦════════╗ ║ start ║ end ║ duration ║ type ║ ╠════════════════╬════════════════╬══════════╬════════╣ ║ 1/06/2015 1:00 ║ 1/06/2015 1:30 ║ 0:30 ║ logged ║ ║ 1/06/2015 2:00 ║ 1/06/2015 3:00 ║ 1:00 ║ logged ║ ║ 1/06/2015 3:20 ║ 1/06/2015 4:00 ║ 0:40 ║ logged ║ ║ 1/06/2015 4:00 ║ null ║ ║ logged ║ ╚════════════════╩════════════════╩══════════╩════════╝
result:
╔════════════════╦════════════════╦══════════╦════════╗ ║ start ║ end ║ duration ║ type ║ ╠════════════════╬════════════════╬══════════╬════════╣ ║ 1/06/2015 1:00 ║ 1/06/2015 1:30 ║ 0:30 ║ logged ║ ║ 1/06/2015 1:30 ║ 1/06/2015 2:00 ║ 0:30 ║ break ║ ║ 1/06/2015 2:00 ║ 1/06/2015 3:00 ║ 1:00 ║ logged ║ ║ 1/06/2015 3:00 ║ 1/06/2015 3:20 ║ 0:20 ║ break ║ ║ 1/06/2015 3:20 ║ 1/06/2015 4:00 ║ 0:40 ║ logged ║ ║ 1/06/2015 4:00 ║ null ║ ║ logged ║ ╚════════════════╩════════════════╩══════════╩════════╝
here 1 solution:
declare @t table ( starttime datetime , endtime datetime, empid int ) insert @t values ( '1/06/2015 1:00', '1/06/2015 1:30', 1 ), ( '1/06/2015 2:00', '1/06/2015 3:00', 1 ), ( '1/06/2015 3:20', '1/06/2015 4:00', 1 ), ( '1/06/2015 4:00', null, 1 ), ( '1/06/2015 1:00', '1/06/2015 1:20', 2 ), ( '1/06/2015 2:10', '1/06/2015 3:10', 2 ), ( '1/06/2015 3:20', '1/06/2015 3:30', 2 ) select starttime, endtime, duration, empid, logged ( select starttime , endtime , datediff(mi, starttime, endtime) duration , empid, 'logged' logged, 1 includerow @t union select endtime , lead(starttime) on (partition empid order starttime ) , datediff(mi, endtime, lead(starttime) on (partition empid order starttime ) ) , empid, 'break' logged, case when endtime null 1 else 0 end includerow @t ) t (t.starttime not null or endtime not null) , (duration > 0 or t.includerow = 1) order t.empid, t.starttime
output:
starttime endtime duration empid logged 2015-01-06 01:00:00.000 2015-01-06 01:30:00.000 30 1 logged 2015-01-06 01:30:00.000 2015-01-06 02:00:00.000 30 1 break 2015-01-06 02:00:00.000 2015-01-06 03:00:00.000 60 1 logged 2015-01-06 03:00:00.000 2015-01-06 03:20:00.000 20 1 break 2015-01-06 03:20:00.000 2015-01-06 04:00:00.000 40 1 logged 2015-01-06 04:00:00.000 null null 1 logged 2015-01-06 01:00:00.000 2015-01-06 01:20:00.000 20 2 logged 2015-01-06 01:20:00.000 2015-01-06 02:10:00.000 50 2 break 2015-01-06 02:10:00.000 2015-01-06 03:10:00.000 60 2 logged 2015-01-06 03:10:00.000 2015-01-06 03:20:00.000 10 2 break 2015-01-06 03:20:00.000 2015-01-06 03:30:00.000 10 2 logged
you selecting first initial rows table, , endtime
each row startime
next row(lead
window function). union
ing results.
Comments
Post a Comment