Step 1 - Fill in the blanks (maybe not necessary)
If your stock table does not contain stocks from each day for each product, then you should get all the dates in a month from another place. You can generate them using recursive CTE: (variable declarations omitted)
with dates as ( select @startdate as [date] union ALL select [date] + 1 from dates where [date] < @enddate ) select @strDays = COALESCE(@strDays + ', ['+ convert(varchar(8), [date],112) + ']', '['+ convert(varchar(8), [date],112) + ']') from dates;
You can use your preferred date format, but itβs important to keep it in all queries.
Step 2 - Bring the data into normal form. You can save it in a temporary table or use CTE again and combine this step with step 3.
Attach dates
(top) using products
(full) and stock
(left) to get the table as follows:
date product_id items
For products and dates when stock is not available, you show 0. isnull
will do the trick. Make sure the date
column is converted to varchar
in the same format as in the CTE above.
Step 3 - rotate the table (obtained in step 2) with the date
column in the dynamic query.
I can give you more details, but not now. You can see something like this in another answer: Distribute different values ββacross different columns
source share