1

I am transforming data from this legacy table: 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

... I want the result to be the following:

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

Can someone help me?

4

1 回答 1

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;
于 2012-06-06T16:38:27.507 回答