我正在转换此旧表中的数据: MovTime(IdMov INT,IdPerson NVARCHAR(20),Date1 datetime,Type1 nvarchar(30))
IdMov IdPerson Date1 Type
----------- -------------------- ----------------------- ------------------------------
1 David 2012-06-01 09:00:00.000 Entered
2 David 2012-06-01 12:30:00.000 Exit
3 David 2012-06-01 14:00:00.000 Entered
4 David 2012-06-01 18:30:00.000 Exit
5 Kim 2012-06-02 09:00:00.000 Entered
6 Kim 2012-06-02 12:00:00.000 Exit
...我希望结果如下:
IdPerson Data Total Time
---------- ---------- ----------
David 2012-06-01 08:00:00
Kim 2012-06-02 03:00:00
T-SQL
declare @WK_TABLE TABLE (IdMov INT, IdPerson NVARCHAR(20), Date1 datetime, Type1 nvarchar(30))
Insert into @WK_TABLE values(1,'David', '2012-06-01 09:00', 'Entered')
Insert into @WK_TABLE values(2,'David', '2012-06-01 12:30', 'Exit')
Insert into @WK_TABLE values(3,'David', '2012-06-01 14:00', 'Entered')
Insert into @WK_TABLE values(4,'David', '2012-06-01 18:30', 'Exit')
Insert into @WK_TABLE values(5,'Kim', '2012-06-02 09:00', 'Entered')
Insert into @WK_TABLE values(6,'Kim', '2012-06-02 12:00', 'Exit')
select * from @WK_TABLE
有人可以帮助我吗?
答案 0 :(得分:1)
假设任何转换都不能超过24小时(例如延伸到第二天),并且有一些约束阻止行没有相应的进入/退出:
;WITH x AS
(
SELECT IdPerson, Date1, Type1, rn = ROW_NUMBER()
OVER (PARTITION BY IdPerson ORDER BY Date1)
FROM @WK_TABLE
)
SELECT
x.IdPerson, [Data] = CONVERT(DATE, x.Date1),
[Total Time] = CONVERT(TIME(0), DATEADD(MINUTE,
SUM(DATEDIFF(MINUTE, x.Date1, x2.Date1)), '00:00:00'))
FROM x INNER JOIN x AS x2
ON x.IdPerson = x2.IdPerson
AND x.rn = x2.rn - 1
AND x.TYpe1 = 'Entered' AND x2.type1 = 'Exit'
GROUP BY x.IdPerson, CONVERT(DATE, x.Date1)
ORDER BY [Data], IdPerson;