在SQL SERVER中查找日期范围(从日期到日期)的周数

时间:2013-09-17 05:50:25

标签: sql sql-server-2008

我有两个日期FromDateToDate。始终星期一ToDate始终星期五

  • 我想分别找几个星期而不只是数。
  • 我想在给定的日期范围内显示第1周,第2周,第3周等报告。 (即每周产品数量)。

我试过这个:

SELECT * FROM WeekDate
WHERE DATEDIFF(Week,GETDATE(),'2013-09-20')=0

它不仅为第0周提供所有值。 任何人都可以帮我解决这个问题吗?

表格结构

CREATE TABLE [dbo].[WeekDate]
(
    [id] [int] IDENTITY(1,1) NOT NULL,
    [Counter] [int] NULL,
    [CDate] [datetime] NOT NULL
) ON [PRIMARY] 

和数据

1   1   2013-09-17 00:00:00.000 
3   2   2013-09-18 00:00:00.000 
4   6   2013-09-19 00:00:00.000 
5   2   2013-09-23 00:00:00.000 
6   3   2013-09-24 00:00:00.000 
7   4   2013-10-01 00:00:00.000 

2 个答案:

答案 0 :(得分:1)

很难说没有输出的例子,但可能是这样的:

select
    sum(Counter),
    datediff(day, @FromDate, CDate) / 7 as ddiff
from WeekDate
-- if you need to filter out rows
where CDate >= @FromDate and CDate <= @ToDate
group by datediff(day, @FromDate, CDate) / 7

<强> sql fiddle demo

答案 1 :(得分:0)

我认为你想要每周一次的产品总和,如果是这样的话,那就试试这个,因为你说开始日期为星期一,结束日期为星期五

declare @StartDate datetime,
        @EndDate datetime;

select  @StartDate = '2013-09-16',
        @EndDate = '2013-10-04';

;with cte as
(
  select @StartDate StartDate, 
    DATEADD(wk, DATEDIFF(wk, 0, @StartDate), 6) EndDate
  union all
  select dateadd(ww, 1, StartDate),
    dateadd(ww, 1, EndDate)
  from cte
  where dateadd(ww, 1, StartDate)<=  @EndDate
)
select (Select COUNT(Cdate) from WeekDate where Cdate between StartDate and EndDate) count1 , StartDate , EndDate
from cte