Home Forums SQL Server 2008 T-SQL (SS2K8) SQL - Need to add a flag when certain conditions are met RE: SQL - Need to add a flag when certain conditions are met

  • One more option (may not be the best but it works).

    create table #temp(Person nvarchar(50),TrnDt date, StartDt date, EndDt date,In_Punch time, Out_Punch time,WkHours int, PayCode nvarchar(50),[XFlag] int)

    insert#temp([Person],[TrnDt],[StartDt],[EndDt],[In_Punch],[Out_Punch],[WkHours],[PayCode])

    SELECT 1234,'08/03/2015','08/03/2015','08/03/2015', '06:00','09:00','3', 'REG1' UNION ALL

    SELECT 1234,'08/03/2015','08/03/2015','08/03/2015', '09:00','13:00','4','REG2' UNION ALL

    SELECT 1234,'08/04/2015','08/04/2015','08/04/2015', '09:00','13:00','4','LEAVE1' UNION ALL

    SELECT 1234,'08/04/2015','08/04/2015','08/04/2015', '14:00','16:00','2', 'LEAVE2'UNION ALL

    SELECT 1234,'08/05/2015','08/05/2015','08/05/2015', '08:00','09:00','1', 'LEAVE1'UNION ALL

    SELECT 4553,'08/05/2015','08/05/2015','08/05/2015', '08:00','09:00','1', 'REG1'UNION ALL

    SELECT 4553,'08/05/2015','08/05/2015','08/05/2015', '10:00','12:00','2','LEAVE2'

    select [Person],[StartDt],[EndDt], Count(*) 'RowCnt' into #x

    from #temp a where a.[PayCode] in ('LEAVE1') and exists (select 1 from #temp b where a.[Person] = b.[Person] and a.StartDt = b.StartDt and b.PayCode = 'LEAVE2')

    group by [Person],[StartDt],[EndDt]

    updateA

    setA.[XFlag] = case when A.[PayCode] = 'LEAVE1' then 1 when A.[PayCode] = 'LEAVE2' then 2 else NULL end

    from#temp A

    INNER JOIN #x b on a.[Person] = b.[Person] and a.[StartDt] = b.[StartDt] and a.[EndDt] = b.[EndDt]

    select * from #temp