按周分组连续几年

时间:2016-11-01 19:47:52

标签: sql sql-server tsql

我正在尝试按周汇总数据。我的示例查询看起来像

SET DATEFIRST 1 

Select  ID, 
DATENAME(week, p.SellingDate) as SellingWeek, 
DATENAME(year, p.SellingDate) as SellingYear,
SUM(Quantity), 
SUM(Revenue)
 From dbo.Sales 
Where       
 p.SellingDate >=’2015-12-20’ and P.SellingDate < ’2016-02-27’
Group by ID,
DATENAME(week, p.SellingDate), 
  DATENAME(year, p.SellingDate)

当我尝试这样做时,我遇到了一个问题:

查询返回正确的数据,但问题出现在2015年的最后一周。它仅考虑2015年为第53周的日期(12/28至12/31),并考虑剩余部分(01 / 01到01/03)作为2016年的新周。我只有一行有整周的数据,即12/28到01/03)但SQL Server返回2行。有解决方法吗?

2 个答案:

答案 0 :(得分:1)

我认为你想要创建一个用于在周开始和周末分组的构造,然后使用它来分组你的聚合子句。

#Input:

lst2 = [['.', 'W', 'W', 'E', 'E'],
        ['.', '.', '.', '.', 'f'],
        ['A', 'A', 'A', '.', 'f']]

#Output: is_space_occupied(0, 1, lst2) should return True because 'W' is present on that spot 
        while is_space_occupied(1, 1, lst2) should return False because '.' is present on 
        that spot and not a letter.

答案 1 :(得分:0)

您可以通过设置周不是基于销售日期而是根据销售日期的星期一来解决此问题。

select 
getdate() as today
datename(week, dateadd(dd,-1* (datepart(weekday, getdate())-1),getdate())) as monday,