При условии, что нет 2-й смены, которая начинается в один день и заканчивается в следующий ...
Таблица:
DECLARE @table TABLE
(
[ID] INT IDENTITY,
[Card] INT,
[PunchDate] DATETIME,
[PunchTime] DATETIME,
[In/Out] TINYINT
)
INSERT INTO @table
(
[Card],
[PunchDate],
[PunchTime],
[In/Out]
)
SELECT 00123,
'3/17/2012',
'3/17/2012 13:00',
1
UNION ALL
SELECT 00123,
'3/17/2012',
'3/17/2012 17:00',
2
UNION ALL
SELECT 00123,
'3/17/2012',
'3/17/2012 17:00',
1
UNION ALL
SELECT 00123,
'3/17/2012',
'3/17/2012 20:00',
2
UNION ALL
SELECT 00456,
'3/17/2012',
'3/17/2012 14:00',
1
UNION ALL
SELECT 00456,
'3/17/2012',
'3/17/2012 17:00',
2
Запрос:
SELECT [Card],
[PunchDate],
MIN([PunchTime]) [PunchTime],
[In/Out]
FROM @table
WHERE [In/Out] = 1
GROUP BY [Card],
[PunchDate],
[In/Out]
UNION
SELECT [Card],
[PunchDate],
MAX([PunchTime]) [PunchTime],
[In/Out]
FROM @table
WHERE [In/Out] = 2
GROUP BY [Card],
[PunchDate],
[In/Out]
ORDER BY [Card],
[PunchDate]
Результат:
Card PunchDate PunchTime In/Out
123 2012-03-17 00:00:00.000 2012-03-17 13:00:00.000 1
123 2012-03-17 00:00:00.000 2012-03-17 20:00:00.000 2
456 2012-03-17 00:00:00.000 2012-03-17 14:00:00.000 1
456 2012-03-17 00:00:00.000 2012-03-17 17:00:00.000 2
Далее он захочет это:
SELECT a.[Card],
a.[PunchDate],
a.[PunchTime],
b.[PunchTime],
DATEDIFF(hour, a.[PunchTime], b.[PunchTime]) TotalTime
FROM (
SELECT [Card],
[PunchDate],
MIN([PunchTime]) [PunchTime]
FROM @table
WHERE [In/Out] = 1
GROUP BY [Card],
[PunchDate]
) a
INNER JOIN (
SELECT [Card],
[PunchDate],
MAX([PunchTime]) [PunchTime]
FROM @table
WHERE [In/Out] = 2
GROUP BY [Card],
[PunchDate]
) b
ON a.[Card] = b.[Card]
AND a.[PunchDate] = b.[PunchDate]
ORDER BY a.[Card],
a.[PunchDate]
Результат
Card PunchDate PunchTime PunchTime TotalTime
123 2012-03-17 00:00:00.000 2012-03-17 13:00:00.000 2012-03-17 20:00:00.000 7
456 2012-03-17 00:00:00.000 2012-03-17 14:00:00.000 2012-03-17 17:00:00.000 3