SQL表更新

时间:2013-03-25 14:40:17

标签: sql

我有两个表如下,我需要使用WorksTracking

中的数据更新WorksOperation表

WorksTracking表。

ID  WorksID  WorksOperationID  DateTime                 SubOperationID  EmployeeID 
1   2182     5363              2012-11-26 12:30:00.000  3               96
2   6866     9856              2012-11-26 10:26:00.000  3               100
3   2182     5363              2012-11-26 16:13:00.000  4               96
4   6866     9856              2012-11-26 13:42:00.000  4               100
6   2182     5363              2012-11-26 06:30:00.000  3               96
7   2182     5363              2012-11-26 12:30:00.000  4               96

SubOperationID = 3 =开始4 =结束

这就是我需要的东西

WorksOperation表。

ID  WorksID  WorksOperationID  StartTime                EndTime                SubOpID  EmpID 
1   2182     5363              2012-11-26 12:30:00.000  2012-11-26 16:13:00.000  4       96
2   6866     9856              2012-11-26 10:26:00.000  2012-11-26 13:42:00.000  4       100
3   2182     5363              2012-11-26 06:30:00.000  2012-11-26 12:30:00.000  4       96

1 个答案:

答案 0 :(得分:0)

这将适用于SQL Server(2005及更高版本),但如果这不是您的RDBMS,则可以轻松地进行调整:

    ;WITH ALLSTARTS AS 
( 
    SELECT * FROM WorksTracking WHERE SubOperationID = 3
)
--INSERT INTO WorksOperation 
SELECT  s.WorksID ,
        s.WorksOperationID ,
        s.DateTime AS StartTime,
        e.DateTime AS EndTime,
        e.SubOperationID AS SubOpID,
        e.EmployeeID FROM ALLSTARTS s 
INNER JOIN dbo.WorksTracking e ON e.SubOperationID = 4 
AND e.DateTime = (SELECT MIN(e.DateTime) FROM WorksTracking e WHERE s.WorksID = e.WorksID AND s.WorksOperationID = e.WorksOperationID AND e.DateTime>s.DateTime)

SqlFiddle