We have a report that needs to get data for 7 days into a result table like this:
declare @table table (ProductId int, product nvarchar(255), supplier nvarchar(255), day1 int, day2 int, day3 int, day4 int, day5 int, day6 int, day7 int)
However the problem is that I currently run 7 insert statements that are nearly identical.
insert @table (ProductId, product, supplier, day1)
select
productId,
product,
supplier,
COUNT(productId)
from
@results
where
createdDate = @Date
group by
CreatedDate, ProductId, Product, supplier
This one inserts into day1, however I have to do the same with day2, day3.... just changing the @Date
What I would like to do is create a loop that will insert into the correct column depending which is the current loop (ie. is is processing day1, or day2...).
Is there a way to dynamically set it to the correct column name for the insert statement?
I'm using: sql server 2008R2