Is this possible with the Sql 2005 CTE?

I am working on a request that will return the proposed start date for the production line based on the set date and the number of minutes required to complete the task.

There is a calendar table (LINE_ID, CALENDAR_DATE, SCHEDULED_MINUTES), which is displayed on each production line, the number of minutes scheduled for this day.

Example: (Usually 3 shifts cost time per day, seven days a week, but may vary)

1, 06/8/2010 00:00:00.000, 1440
1, 06/7/2010 00:00:00.000, 1440
1, 06/6/2010 00:00:00.000, 0
1, 06/5/2010 00:00:00.000, 0
1, 06/4/2010 00:00:00.000, 1440

To get the suggested start date, I need to start from the set date and iterate down for days until I have enough time to complete the task.

My question may be how it is done with CTE, or this is what should be handled by the cursor. Or ... am I just going completely different?

+3
source share
2 answers

will there be something like this work?

;WITH CALENDAR_WITH_INDEX(CALENDAR_DATE, AVAILABLE_MINUTES, DATE_INDEX)
(
     SELECT
          CALENDAR_DATE,
          1440 - SCHEDULED_MINUTES,               /* convert scheduled minutes to available minutes */
          ROW_NUMBER() OVER (ORDER BY CALENDAR_DATE DESC) /* get day indexes. can't use DATE functions to get previous day (think holidays) */
     FROM
          CALENDAR
     WHERE
          LINE_ID = @LINE_ID AND
          CALENDAR_DATE < @DUEDATE                        /* use <= instead of < if you can do stuff on the scheduled date too */
),
WITH TIME_SLICES (SCHEDULED_DATE, MINUTESPENDING, SLICE_INDEX)
(
     SELECT 
          CALENDAR_DATE, 
          @DURATION - (AVAILABLE_MINUTES),                /* knocks of minutes available from our running total */
          DATE_INDEX
     FROM 
          CALENDAR_WITH_INDEX                             
     WHERE
          DATE_INDEX = 1                                  /* gets the first date usable date */

     UNION ALL

     SELECT 
          CALENDAR_DATE, 
          MINUTESPENDING - AVAILABLE_MINUTES
          DATE_INDEX
     FROM 
          CALENDAR_WITH_INDEX
          INNER JOIN TIME_SLICES 
               ON DATE_INDEX = SLICE_INDEX + 1            /* this gets us the date 1 day before */
     WHERE
          MINUTESPENDING > 0                              /* stop when we have no more minutes */
)
SELECT MIN(SCHEDULED_DATE) FROM TIME_SLICES

I think performance will be poor due to row_number, the recursive part.

+1
source

It is possible, but slower to use the Common Table expression to calculate the total. This is one of the few cases where the cursor works better.

+1
source

Source: https://habr.com/ru/post/1749235/


All Articles