SQL Server:一个日历月内的整周总计

时间:2016-10-17 13:24:59

标签: sql sql-server

我想要一个月内的每周总数。它不包括任何部分周或未来周。周从星期一到星期日开始。

我有一个类似

的表结构
Date          Value      -- Comments
----------------------------------------------------------------------   
2016-10-01      7        Ignore this because its not a whole  week in a month
2016-10-05      8        Week 1  
2016-10-07      5        Week 1  
2016-10-11      2        Week 2  
2016-10-15      1        Week 2    
2016-10-17      9        Ignore this because the week is not finished yet

输出

 WeekNo         Total
    41             13
    42              3

4 个答案:

答案 0 :(得分:1)

更简单的方法是建立一个Tally" date"表。 你可以从任何Tally表中生成它,如:

DECLARE @StartDate DATE = '20160101'
  , @EndDate DATE = '20161231';

WITH cte AS (
SELECT  DATEADD(DAY, n - 1, @StartDate) AS date
FROM    tally
WHERE   n - 1 <= DATEDIFF(DAY, @StartDate, @EndDate)
)
SELECT 
    c.date 
    ,YEAR(c.date) AS Year
    ,MONTH(c.date) AS Month
    ,DAY(c.date) AS Month
    ,DATEPART(WEEK,c.date) AS Week
    ,CASE WHEN 7<>COUNT(c.date) OVER (PARTITION BY YEAR(c.date),MONTH(c.date),DATEPART(WEEK,c.date)) THEN  0 ELSE 1 END AS isFullWeek
FROM cte c

然后你只需要将它加入到你需要的查询中。

答案 1 :(得分:1)

DECLARE @StartDate datetime = '2011-10-01';
DECLARE @EndDate datetime = '2016-10-31';
SELECT
  CAST(DATEADD(dd, -DATEPART(dw, tblData.RecordDate) + 2, tblData.RecordDate) AS date) AS WeekStart,
  CAST(DATEADD(dd, -DATEPART(dw, tblData.RecordDate) + 8, tblData.RecordDate) AS date) AS WeekEnd,
  SUM(Value) AS Total
FROM tblData

WHERE (@StartDate IS NULL
OR CAST(DATEADD(dd, -DATEPART(dw, tblData.RecordDate) + 2, tblData.RecordDate) AS date) >= CAST(@StartDate AS date))
AND (@EndDate IS NULL
OR CAST(DATEADD(dd, -DATEPART(dw, tblData.RecordDate) + 8, tblData.RecordDate) AS date) <= CAST(@EndDate AS date))
AND CAST(DATEADD(dd, -DATEPART(dw, tblData.RecordDate) + 8, tblData.RecordDate) AS date) < CAST(GETDATE() AS date)
GROUP BY CAST(DATEADD(dd, -DATEPART(dw, tblData.RecordDate) + 2, tblData.RecordDate) AS date),
         CAST(DATEADD(dd, -DATEPART(dw, tblData.RecordDate) + 8, tblData.RecordDate) AS date)

答案 2 :(得分:0)

创建符合您要求的日历表,如下所示:

    create table calendarTable ([date] date, weekNro int)
        go

    insert into  calendarTable 
    select dateadd(d,n,'20160101'), DATEPART(WK,dateadd(d,n,'20151231')) 
    from  numbers where n<500

如果您没有Numbers Table,则必须先创建它。像这样

SET NOCOUNT ON    
CREATE TABLE Numbers (n bigint PRIMARY KEY)    
GO    
DECLARE @numbers table(number int);  
WITH numbers(number) as  (   
SELECT 1 AS number   
UNION all   
SELECT number+1 FROM numbers WHERE number<10000  
)  
INSERT INTO @numbers(number)  
SELECT number FROM numbers OPTION(maxrecursion 10000)
INSERT INTO Numbers(n)  SELECT number FROM @numbers

然后查询加入日历表的表格,记住完成周的实际日期,如下所示:

答案 3 :(得分:-1)

    Select DATEPART(ww, date) , SUM(Case When Comments Like '%1' then Value when Comments Like '%2' then Value else Value end)

from schema.tablename

group by DATEPART(ww,date)

对不起,如果这不起作用,这是我想要构建它的唯一方法。