Question : SQL Lookup table with multiple references based on update date field

Hello,

Trying to wrap my head around the best approach with this.  One table tracks the status of a staff member with whatever code they select.  It records the date and time in which they make their selection.

Another table stores the description of the codes available.  It also stores the date in which that code was updated (which can also apply to it being created).  So you could potentially have the same code repeated but with different dates.

So what I would like to do is produce a report which reports the correct code for the date the selection was made.  In the example attached, August 20th Code 2 meant they were on break.  But by August 23rd, code 2 has changed to On Phone.  So for all days between Aug 20th and Aug 22nd it should report it as On Break.  After the 23rd it should report it as On Phone.  

How would this be constructed in SQL? (I include my weak and feable attempt as it doesnt work)
1:
2:
3:
SELECT *
  FROM CodeLogging log
 INNER JOIN CodeReference ref ON log.code = ref.code AND log.Date >= ref.LastUpdate
Attachments:
 
Example Tables and expected output
 

Answer : SQL Lookup table with multiple references based on update date field

You could create a days calendar and join your tables to it
CREATE FUNCTION [dbo].[DAY_CALENDAR]
(
      @StartDate TDATETIME,
      @EndDate TDATETIME
)
RETURNS
      @DYCALENDAR TABLE
(
      StartDate DATETIME,
      EndDate DATETIME,
      OnDay DATETIME
)
AS
BEGIN
      DECLARE @varStartTime TDATETIME, @varEndTime TDATETIME
      
      set @varStartTime = DATEADD(dd, 0, DATEDIFF(dd, 0, @StartDate))
      
      while @varStartTime <= @EndDate
      begin
            set @varEndTime = DATEADD(DD, 1, @varStartTime) --end time
            set @varRes = @varStartTime
            
            insert into @DYCALENDAR
            values (@varStartTime, @varEndTime, @varStartTime)
            
            set @varStartTime = @varEndTime
      end            
      
      RETURN
END
       
Query
SELECT *
FROM CodeLogging log
INNER JOIN CodeReference ref ON log.code = ref.code
INNER JOIN  DAY_CALENDAR(08/01/2010', '08/31/2010') LOGDAYS ON
  (log.date >= LOGDAYS.StartDate  and log.Date < LOGDAYS.EndDate)

Random Solutions  
 
programming4us programming4us