Project Allocation Across Start and End Dates

vvs1257 1 Reputation point
2021-01-28T22:11:32.06+00:00

I have the following code which returns a date table:

DECLARE @StartDate  date = '20150101';  
  
DECLARE @CutoffDate date = DATEADD(DAY, -1, DATEADD(YEAR, 10, @StartDate));  
  
;WITH seq(n) AS   
(  
  SELECT 0 UNION ALL SELECT n + 1 FROM seq  
  WHERE n < DATEDIFF(DAY, @StartDate, @CutoffDate)  
),  
d(d) AS   
(  
  SELECT DATEADD(DAY, n, @StartDate) FROM seq  
),  
src AS  
(  
  SELECT  
    TheDate         = CONVERT(date, d),  
     
    TheDayName      = DATENAME(WEEKDAY,   d),  
    TheWeek         = DATEPART(WEEK,      d),  
    TheISOWeek      = DATEPART(ISO_WEEK,  d)  
  FROM d  
)  
SELECT * FROM src  
  ORDER BY TheDate  
  OPTION (MAXRECURSION 0);  

And then I have my transaction data which is based solely on start and end date. I need to get the amount and divide by the number of weeks between the start and end date, and extract an Allocation Amt and Allocate Date for each week contained within the start and the end dates.

Here is my sample data:

Declare @D as Table (ProjectId Int, ProjDesc varchar(30), StartDate date, EndDate date, ProjectAmt numeric(19,5))  
  
Insert into @D(ProjectId , ProjDesc , StartDate , EndDate , ProjectAmt )  
VALUES  
(1, 'Project1', '2020-05-01', '2020-12-15',15000),  
(2, 'Project2', '2021-03-01', '2021-12-15',25500),  
(3, 'Project3', '2021-02-01', '2021-03-15',50000),  
(4, 'Project4', '2021-04-15', '2021-09-15',75000),  
(5, 'Project5', '2021-01-01', '2021-05-01',18000)  
  
Select   
ProjectId,   
ProjDesc,   
StartDate,   
EndDate,   
datediff(ww,startdate,enddate) as WeekCount,  
  
TranMonth=DATEPART(WEEK,      startdate),  
ProjectAmt,  
ProjectAllocateAmt=ProjectAmt/datediff(ww,startdate,enddate)   
from @D  

And the output I am trying to receive is this:
61612-allocate.png

Developer technologies | Transact-SQL
0 comments No comments
{count} votes

7 answers

Sort by: Most helpful
  1. vvs1257 1 Reputation point
    2021-01-29T20:34:15.647+00:00

    I'm a little confused by
    NorthNumbers..Numbers n ON n.n BETWEEN 1 AND CTE.WeekCount
    I don't see how that works in what is trying to be accomplished.


  2. vvs1257 1 Reputation point
    2021-01-29T20:56:32.167+00:00

    Here is a week query based upon a date table, since it includes the year and the week this should handle threshold years.

    Still have the questions noted above.

    Thank you

    SELECT TheDate,   TheDateYear,   TheDateWeek
    FROM   (
       SELECT TheDate, DatePart(Year, TheDate) as TheDateYear, DatePart(Week, TheDate) as TheDateWeek,
            row_number() OVER(PARTITION BY DatePart(Year, TheDate),DatePart(Week, TheDate)  ORDER BY TheDate ASC) AS rn
       FROM   DateTable
       ) sub
    WHERE  rn = 1;
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.