SQL运行变量+1直到变量达到52?

时间:2015-07-08 19:04:20

标签: sql sql-server sql-server-2008

我有一个基本上是:

declare @StartDate date
declare @EndDate date
declare @WeekNumber int

set @StartDate = '01/06/2014'
set @EndDate = '07/06/2015'
set @WeekNumber = 01

select @WeekNumber [WeekNumber]
,dateadd(ww,(@WeekNumber-1),@startDate) [WeekStartDate]
,dateadd(dd,6,dateadd(ww,(@WeekNumber-1),@startDate)) [WeekEndDate]
,* 
From (Select t1.LeadSource
                    ,count(t1.prospectid) [Leads]
                    ,sum(t1.Found) [Apps]
        from Table T1 
        where t1.CreateDate between dateadd(ww,(@WeekNumber-1),@startDate)
            and cast(convert(varchar(10),dateadd(dd,6,dateadd(ww,(@WeekNumber-1),@startDate)),101) as datetime)) f
GROUP BY f.LeadSource

这将是它返回时的样子

WeekNumber  WeekStartDate   WeekEndDate Leads  Apps 
1           2014-01-06      2014-01-12  30     3    

我需要在过去的两年中运行它,如果有意义的话,它会在每周循环并按周数返回。

有没有办法循环@WeekNumber变量,并在它达到52周甚至104时停止?

感谢您的时间。

2 个答案:

答案 0 :(得分:2)

如果你在考虑循环,那么你就走错了路。您需要考虑基于集合的逻辑。你需要做的是完全摆脱@weeknumber变量,只是以不同的方式对数据进行分组。您希望按周分组,因此您需要计算周数。您可以使用DATEDIFF()和DATEPART(dw,...)执行此操作:

declare @StartDate date
declare @EndDate date
declare @WeekNumber int

set @StartDate = '01/06/2014'
set @EndDate = '07/06/2015'
--set @WeekNumber = 01

select datediff(ww,@startdate,[WeekStartDate])+1 [WeekNumber]
,[WeekStartDate]
,dateadd(dd,6,[WeekStartDate]) [WeekEndDate]
,* 
From (Select t1.LeadSource
                    ,count(t1.prospectid) [Leads]
                    ,sum(t1.Found) [Apps]
                    ,dateadd(dd,2-datepart(dw,t1.CreateDate),t1.CreateDate) WeekStartDate
        from Table T1 
        where t1.CreateDate between @startDate
            and @enddate
GROUP BY f.LeadSource ) f

答案 1 :(得分:0)

一种有趣的方式可能是这样的:

我在我的数据库中使用这样的函数,以便在需要时生成一组正在运行的数字...

CREATE FUNCTION dbo.RunningNumber(@Counter AS INT)
RETURNS TABLE
AS
RETURN
SELECT TOP (@Counter) ROW_NUMBER() OVER(ORDER BY o.object_id) AS RunningNummber
FROM sys.objects AS o; --take any large table here...
GO
SELECT * FROM dbo.RunningNumber(100)

确保使用的@Counter不高于您使用的表的行数。你可以将它加入给定的SELECT,然后使用Modulo 7(% 7)进行分组......