根据SQL中的表值更新其他表

时间:2016-07-22 15:25:43

标签: sql

我有两个名为EmployeeTime的表。如果员工代码1E的所有TaskList都是y,我想分配OnTrack=y

我试过了,我被困了

UPDATE Employee
SET OnTrack = 'y'
FROM Employee e
WHERE e.Code IN 
INNER JOIN (SELECT EmployeeCode FROM Time WHERE status = 'P') permanent
ON permanent.Employeecode = e.Code
AND permanent.Employeecode NOT IN
(SELECT EmployeeCode FROM Time t WHERE t.EmployeeCode=permanent.Employeecode and t.tasklist<>'y' )

我的代码只更新了一行。有人可以帮忙吗?

员工表:

Code    Name    Hours   OnTrack  
***********************************  
1E     SCOTT    32  
2E     LISA     32  
3E     MARK     32  

时间表是

Code    Employeecode    Status  workingHours    TaskList  
********************************************************  
1A          1E             P      8               Y  
2A          1E             P      8               Y  
3A          1E             P      8               N  
4A          2E             T      8               Y  
5A          2E             T      0               Y  
6A          3E             P      8               Y  

结果是员工表中的预期结果,如果其所有员工代码在时间表中的“Y”如下所示,则应更新OnTrack状态:

Code    Name    Hours   OnTrack  

1E      SCOTT    24      N  
2E      LISA      12     Y  
3E      MARK      0      Y  

2 个答案:

答案 0 :(得分:1)

(假设您使用的是SQL Server)首先尝试选择stmt,如果结果使用下面的更新stmt。很难在不看表的情况下编写代码,但只是按照你的解释,这应该会让你朝着正确的方向前进。

select * 
FROM Employee e 
INNER JOIN TIME t1 ON t1.EmployeeCode  =   e.code 
INNER JOIN TIME t2 ON t2.EmployeeCode  <>  e.code 
WHERE t1.status    = 'P' 
AND   t2.tasklist <> 'y'

请勿在不尝试上述选择

的情况下运行此操作
UPDATE Employee
SET OnTrack = 'y'
FROM Employee e 
INNER JOIN TIME t1 ON t1.EmployeeCode   = e.code 
INNER JOIN TIME t2 ON t2.EmployeeCode  <> e.code 
WHERE t1.status    = 'P' 
AND   t2.tasklist <> 'y'

答案 1 :(得分:1)

我用测试数据创建了一些表变量。怎么样:

DECLARE @Time TABLE (Code VARCHAR(2),Employeecode VARCHAR(2),Status CHAR(1), 
                     WorkingHours INT, TaskList CHAR(1))
INSERT @Time
VALUES  ('1A','1E','P',8,'Y'), 
        ('2A','1E','P',8,'Y'),  
        ('3A','1E','P',8,'N'), 
        ('4A','2E','T',8,'Y'),
        ('5A','2E','T',0,'Y'),
        ('6A','3E','P',8,'Y')
DECLARE @Employee TABLE (Code CHAR(2), Name VARCHAR(10), Hours INT, OnTrack CHAR(1))
INSERT @Employee
VALUES  ('1E','SCOTT',32,NULL),
        ('2E','LISA',32,NULL),  
        ('3E','MARK',32,NULL)

UPDATE e
SET e.OnTrack = t.TaskList
FROM @Employee e
JOIN (SELECT Employeecode, MIN(TaskList) TaskList
      FROM @Time
      GROUP BY Employeecode) t ON E.Code = T.Employeecode

SELECT *
FROM @Employee

结果:

Code    Name    Hours   OnTrack
1E      SCOTT   32      N
2E      LISA    32      Y
3E      MARK    32      Y

如果您只想更新永久员工,只需将Status添加到子查询中。

SELECT Employeecode, MIN(TaskList) TaskList
    FROM @Time
    WHERE Status = 'p'
    GROUP BY Employeecode