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)
开发者_如何学Python
When I query for A, I need
Start End
10:12 10:03 (A)
what is the sql query pls. Thanks
Guys, Thanks for your replies. My objective is to calculate a time sheet. Employee will punch in and punch out. I store those records in one table. That table has time and a field for in punch or out punch. Employee may go out for lunch or other reasons and punches for out and in. I need deduct those times and get the working hours. My table will look like below :
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
For (A)'s time 7.14 - 10.01 is the total hours, but he was not there between 12.03 to 01.05 so I need to deduct the lunch time and get the total hours. How to do this in Query
SELECT max(start), min(end) FROM table WHERE column='A';
If you looking for total time this will do it.
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'
This query finds the First PunchTime of a Punch='T' after a Punch='F' (non working times). Then you can simply calculate datediff and similar stuff.
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'
精彩评论