简体   繁体   English

如何使用每周汇总的另一个表中的值创建临时表?

[英]How to create a temp table with values from another table aggregated weekly?

It is a bit difficult to explain but basically I need to create a temporary table (date datetime, #customers int) where #customers is the number of weekly customers pulled from another table. 有点难以解释,但是基本上我需要创建一个临时表(date datetime,#customers int),其中#customers是从另一个表中提取的每周客户数。 Here's my code. 这是我的代码。

declare @date datetime
declare @temptable table (date datetime not null,#customers int)

set @date='2018-02-13'

while @date<getdate()
begin
insert into @temptable values 
(@date,
(select count(*) from in_ft_conversion 
where u4='cfa' and sales_date between @date and @date-7))
set @date=@date+7
end

The result is a table with all the correct date entries but 0 in the customer column... Does anybody know what I'm doing wrong? 结果是一张表,其中所有日期输入均正确,但customer列中为0。有人知道我在做什么错吗? Thanks! 谢谢!

您的日期范围有误,请在BETWEEN中交换日期值,这样您就有了BETWEEN <earlier date> AND <later date>

where u4='cfa' and sales_date between @date-7 and @date))

Why would you use a while loop for this? 为什么要为此使用while循环? I think you want something like this: 我想你想要这样的东西:

insert into @temptable (date, num_customers) 
    select dateadd(day, '2018-02-08', weekno * 7)
           count(*)
    from in_ft_conversion cross apply
         (values (datediff(day, '2018-02-08', sales_date) / 7
         ) v(weekno)
    where u4 = 'cfa' and sales_date >= '2018-02-08'
    group by v.weekno;

No loop is necessary. 无需循环。

Your problem is specifically the between comparison: 您的问题特别是between比较:

sales_date between @date and @date-7

The dates are backwards -- the lower bound needs to go first. 日期是向后的-下限需要先走。

But, I also doubt that you want to count weeks with 8 days and have one day overlap on each week. 但是,我也怀疑您想将8天计算为几周,并且每周有一天重叠。 I think the above logic does what you want, but you can adjust the date arithmetic to get the exact dates you want. 我认为上述逻辑可以满足您的要求,但是您可以调整日期算法以获取所需的确切日期。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM