【问题标题】:Insert last X Week Numbers into Temporary table将最后 X 周的数字插入临时表
【发布时间】:2013-09-18 10:21:36
【问题描述】:

我的问题

我正在尝试编写一个存储过程来检索过去 X 周的周数,然后将它们插入到一个临时表中。

到目前为止,我已经能够创建临时表并返回内容(不是很难)。但是,我现在的问题在于将最后 X 周的数字插入到我的临时表中......我是否使用某种循环?如果是这样,我该怎么做?

请注意,我不能对当前周数进行简单的减法,因为如果当前周数小于 X,这可能会产生负数...必须使用 DATEPART 计算周数每次(我认为)。

我尝试过的...

到目前为止,我的代码如下所示:

-- Declare the variables for the login totals
DECLARE @Current_Week_Number int

-- Get the current week number
SELECT @Current_Week_Number = DATEPART( wk, GETDATE())

-- Create the temporary table
CREATE TABLE #Number_Of_Logins (
    Week_Number tinyint,
    Number_Of_Logins int
)

-- Return the number of logins
SELECT * FROM #Number_Of_Logins

【问题讨论】:

    标签: sql sql-server date stored-procedures temp-tables


    【解决方案1】:

    这样的?

    declare @X int = 3
    
    ;with cte as (
         select 0 as num       
         union all
         select num + 1 from cte where num < @X - 1
    )
    select
        datepart(wk, dateadd(wk, -num, getdate()))
    from cte
    

    sql fiddle demo

    查询由两部分组成。第 1 部分是recursive common table expression。基本上我在这里需要的是建立一个从 0 到 @X - 1 的数字表,如下所示:

     num
     0
     1
     2
    

    之后,我需要计算日期,如当前日期、当前日期 - 1 周、当前日期 - 2 周 - 所以我使用 dateadd() 函数(注意 num 之前的减号,我想减去周数)。现在我只需要通过datepart() 函数计算周数。

    【讨论】:

    • 这看起来很棒,而且看起来很有效。您介意添加一些 cmets,以便我可以尝试找出发生了什么吗?我的 SQL 技能不太好......另外,你能解释一下为什么在with 之前有一个;,以及为什么你有两个select 吗?非常感谢您的帮助,谢谢! +1
    • @BenCarey 添加了一些解释,请随时提问。如果您有一些带有数字的表格,您可以使用它来代替 cte。如果您需要硬编码的周数,您可以使用表值构造函数 - 请参阅此处stackoverflow.com/questions/18833428/…
    • 完美!非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2012-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-02
    • 2015-01-05
    • 1970-01-01
    相关资源
    最近更新 更多