1

我有两个日期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 
4

2 回答 2

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

于 2013-09-17T06:10:01.327 回答
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        
于 2013-09-17T06:06:39.107 回答