我们有一份报告需要将数据获取7天,如下所示:
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)
但问题是我目前运行的7个插入语句几乎相同。
insert @table (ProductId, product, supplier, day1)
select
productId,
product,
supplier,
COUNT(productId)
from
@results
where
createdDate = @Date
group by
CreatedDate, ProductId, Product, supplier
这个插入day1,但是我必须对day2,day3做同样的事情....只是改变@Date
我想要做的是创建一个循环,插入到正确的列中,这取决于当前循环(即处理day1或day2 ......)。
有没有办法动态地将它设置为insert语句的正确列名?
我正在使用:sql server 2008R2
答案 0 :(得分:2)
您是否可以尝试使用SQL-Server 2008中的PIVOT函数在一个查询中完成插入操作?
我假设你的日子是连续的,你的专栏是Day1,Day2等。
;WITH Data AS
( SELECT ProductID,
Product,
Supplier,
DATEDIFF(DAY, @Date, CreatedDate) + 1 AS DayNumber,
ProductID AS [Counter]
FROM @Results
WHERE CreatedDate BETWEEN @Date AND DATEADD(DAY, 7, @Date)
)
INSERT @table (ProductID, Product, Supplier, Day1, Day2, Day3, Day4, Day5, Day6, Day7)
SELECT *
FROM Data
PIVOT
( COUNT([Counter])
FOR DayNumber IN ([1], [2], [3], [4], [5], [6], [7])
) pvt
答案 1 :(得分:1)
如果您在处理SQL问题时发现自己要求使用循环,那么您可能没有使用适当的思维模式来解决问题。
下面的起点。
SELECT productId
, product
, supplier
, day1 = SUM(CASE WHEN createdDate = @date THEN 1 ELSE 0 END)
, day2 = SUM(CASE WHEN createdDate = DATEADD(d,1,@date) THEN 1 ELSE 0 END)...
FROM @results
WHERE createdDate >= @Date
GROUP BY CreatedDate
, ProductId
, Product
, supplier
答案 2 :(得分:0)
我建议你不要这样做,而是将目标表结构改为另外两个名为day_count的列,它存储当天的计数和createdDate
create table @table (productId int,product int, supplier int,
createdDate date,day_count int)
可以使用下面的查询填充此表
insert @table (ProductId, product, supplier,createdDate, day_count)
select
productId,
product,
supplier,
createdDate,
COUNT(productId)
from
@results
where
createdDate between @Date and dateadd(dd, 7, @Date)
group by
CreatedDate, ProductId, Product, supplier
然后使用以下查询获得所需的输出
declare @startDate date ='2012-07-02';
with cte as(
select productId ,product , supplier ,createdDate, datediff(dd,
@startDate,createdDate)+1 [day_num],
day_count from #tmp)
select productId ,product , supplier ,createdDate ,
case when day_num=1 then day_count end [day1],
case when day_num=2 then day_count end [day2],
case when day_num=3 then day_count end [day3],
case when day_num=4 then day_count end [day4],
case when day_num=5 then day_count end [day5],
case when day_num=6 then day_count end [day6],
case when day_num=7 then day_count end [day7]
from cte