Search code examples
sqlsql-serverwhere-clausecorrelated-subquery

Update multiple records based on 1 record meeting a criteria


I am trying to Select all records from a dataset where 1 of the records meets a criteria. I have a table of data that contain the hours worked by a person by day. I need to select all the records for a person for that week, if one record within that week has the 'logged' flag set to 'N'. Here's a data example:

t_hours:

Name  Week  Weekday  Hours  Logged
===============================
Jim   1     Mon      8       Y
Jim   1     Wed      8       Y
Jim   1     Fri      8       Y
Jim   2     Mon      8       Y
Jim   2     Wed      8       Y
Bill  1     Mon      8       N
Bill  1     Tue      8       Y
Bill  1     Wed      8       Y
Bill  1     Thu      8       Y
Bill  2     Mon      8       Y
Bill  2     Tue      8       Y

I want to write a query that will update all the records for a persons workweek to Logged='N', if they have one day where Logged='N'. But I can't figure out how to even select the records. Here are the records that I want to update:

Name  Week  Weekday  Hours  Logged
===============================
Bill  1     Mon      8       N
Bill  1     Tue      8       Y
Bill  1     Wed      8       Y
Bill  1     Thu      8       Y

I have tried a normal select, but can't figure out how to have two correlated subqueries in the where clause:

SELECT * FROM t_hours
WHERE (Name = (SELECT t1.Name FROM t_hours t1 
               where t1.Name = t2.Name and t1.Week = t2.Week and 
               t1.Logged = 'N') and
       Week = (SELECT t2.Week FROM t_hours t2 
               where t1.Name = t2.Name and t1.Week = t2.Week and 
               t2.Logged = 'N')

but this doesn't work, any help is greatly appreciated.


Solution

  • Return data:

     SELECT *
    FROM   t_hours t1
    WHERE  EXISTS (SELECT 1
                   FROM   t_hours t2
                   WHERE  t1.NAME = t2.NAME
                          AND t1.week = t2.week
                          AND t2.logged = 'N');  
    

    Update data:

     UPDATE t_hours
    SET    logged = 'N'
    WHERE  EXISTS (SELECT 1
                   FROM   t_hours t2
                   WHERE  t1.NAME = t2.NAME
                          AND t1.week = t2.week
                          AND t2.logged = 'N');  
    

    If the data set is large enough, you could group by name, week, and logged type.