--===== If the test table already exists, drop it IF OBJECT_ID('TempDB..#mytable','U') IS NOT NULL DROP TABLE #mytable--===== Create the test table with CREATE TABLE #mytable ( EMP_ID INT, Title varchar(50), DateValue DATETIME, TITLE_YEAR INT, )--=======INSERT DATAINSERT INTO #mytable (EMP_ID, TITLE, DATEVALUE)SELECT'1','Managing Director','Jan 1 2009 12:00AM'UNION ALLSELECT'2','Director','Jan 1 2009 12:00AM'UNION ALLSELECT'3','Senior Consultant','Jan 1 2009 12:00AM'UNION ALLSELECT'3','Director','Jan 1 2010 12:00AM'UNION ALLSELECT'2','Director','Jan 1 2010 12:00AM'UNION ALLSELECT'1','SENIOR MANAGING DIRECTOR','Jan 1 2010 12:00AM'UNION ALLSELECT'2','Director','Jan 1 2011 12:00AM'UNION ALLSELECT'3','Director','Jan 1 2011 12:00AM'UNION ALLSELECT'1','SENIOR MANAGING DIRECTOR','Jan 1 2011 12:00AM'UNION ALLSELECT'3','Director','Jan 1 2012 12:00AM'UNION ALLSELECT'2','Senior Director','Jan 1 2012 12:00AM'UNION ALLSELECT'1','Senior Managing Director','Jan 1 2012 12:00AM'UNION ALLSELECT'2','Senior Director','Jan 1 2013 12:00AM'UNION ALLSELECT'1','Senior Managing Director','Jan 1 2013 12:00AM'UNION ALLSELECT'3','Director','Jan 1 2013 12:00AM'UNION ALLSELECT'2','Senior Director','Jan 1 2014 12:00AM'UNION ALLSELECT'1','Senior Managing Director','Jan 1 2014 12:00AM'UNION ALLSELECT'3','Senior Director','Jan 1 2014 12:00AM'I am new to this level of coding in SQL SERVER 2012, but I am looking to update the TITLE_YEAR field in the temp table with the Year the employee is in that title. For example for employee 11127 the data should look like this:EMP_ID Title DateValue TITLE_YEAR3 Senior Consultant 2009-01-01 00:00:00.000 13 Director 2010-01-01 00:00:00.000 13 Director 2011-01-01 00:00:00.000 23 Director 2012-01-01 00:00:00.000 33 Director 2013-01-01 00:00:00.000 43 Senior Director 2014-01-01 00:00:00.000 1I feel like a recursive CTE might accomplish this, but I do not have much experience with recursive CTEs. Any help would be greatly appreciated.
↧