Sum multiple data date columns using a single "as of date" data range

SA Will 0 Reputation points
2023-04-18T17:28:17.28+00:00
The below sql code is my attempt to Sum multiple data date columns 
RECEIVEDATE, TENDERDATE and SHIPDATE 
using a single "as of date" data range

-- Declare variable 
DECLARE @BeginDate date
DECLARE @EndDate date
DECLARE @asofdate date
DECLARE @NumberofDays int = 0
DECLARE @daycnt int = 0 

-- set Begining and Ending date range 
set @BeginDate = '2023-04-15'
Set @EndDate = '2023-04-18'
set @NumberofDays = DateDiff(day, @BeginDate,@EndDate) +1
set @asofdate = @BeginDate 

-- initiate loop ( not to experts - there has to be a better way ) 
while (@daycnt < @NumberofDays)
	begin 

SELECT [VPCCODE], [VPCNAME], @asofdate as 'P_DATE',
		SUM(CASE when CAST(RECEIVEDATE as DATE) = @asofdate THEN 1 else 0 end) AS  RECEIVED,
		SUM(CASE when CAST(TENDERDATE as DATE) = @asofdate THEN 1 else 0 end) AS TENDERED,
		SUM(CASE when CAST(SHIPDATE as DATE) = @asofdate THEN 1 else 0 end) AS SHIPPED

		FROM vpc.Inventory
		WHERE VPCCODE = 091
	
		GROUP BY [VPCCODE],[VPCNAME]
		order by P_DATE

		set @asofdate = DATEADD(day, 1, @asofdate) 
		set @daycnt = @daycnt+1
end


**Current SQL code above creates 4 individual result sets for each P_DATE **





I would like to have 1 result  (se example below

 

  
Please advise if this is possible and assist with code examples.
Thank you in advance for your support



example of vpc.inventory file 



 
SQL Server Other
{count} votes

2 answers

Sort by: Most helpful
  1. Deleted

    This answer has been deleted due to a violation of our Code of Conduct. The answer was manually reported or identified through automated detection before action was taken. Please refer to our Code of Conduct for more information.


    Comments have been turned off. Learn more

  2. LiHongMSFT-4306 31,566 Reputation points
    2023-04-19T03:05:10.93+00:00

    Hi @SA Will

    You could declare a table variable and then inside the While Loop insert the four individual results into this table.

    Check this code.txt

    Best regards,

    Cosmog Hong


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


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.