T-SQL选择按周分组的值,如果一周没有值,则为零

时间:2014-05-20 10:56:56

标签: sql-server date group-by

我试图在SQL Server中按周分组值(销售数据)。对于某一周没有销售的商品,我仍然希望获得周数和年份,总和为0.

销售分类帐表已计算年份和周数的列,我将其分组。

现在我的查询看起来像这样:

select ItemNumber, sum(Amount), year, week 
from JournalPosition 
group by week, year, ItemNumber 
order by ItemNumber asc, year desc, week desc

在不必实施数据仓库的情况下,实现我想要的有效方法是什么? (存储过程或临时表对我来说没问题)

2 个答案:

答案 0 :(得分:0)

您需要生成要包含在查询中并加入其中的所有周的列表。您可以将它们存储在预先生成的表中或使用CTE。这样的事情可以帮助您完成CTE how to get the start and end dates of all weeks between two dates in SQL server?

答案 1 :(得分:0)

您可以使用递归CTE与表格中的日期:

declare @StartDate datetime,@EndDate datetime

set @StartDate=(select convert(varchar,min(Year),102) from JournalPosition)
set @EndDate=(select dateadd(day,-1,dateadd(year,2,convert(varchar,max(Year),102))) from JournalPosition)

print @StartDate
print @EndDate

;with CTE as (
  select @StartDate as StartDate, DATEPART(week,@StartDate) as WeekNumber, DATEPART(year,@StartDate) as YearNumber
  union all
  select DATEADD(week, 1, StartDate), DATEPART(week,DATEADD(WEEK, 1, StartDate)), DATEPART(year,DATEADD(week, 1, StartDate))
  from CTE
  where DATEADD(week, 1, StartDate) <= @EndDate
  )
select ItemNumber, isnull(sum(Amount),0), CTE.YearNumber, datepart(week,CTE.StartDate)
from JournalPosition 
full join CTE
on JournalPosition.week=datepart(week,CTE.StartDate) and JournalPosition.year=CTE.YearNumber
group by CTE.YearNumber, datepart(week,CTE.StartDate), ItemNumber
order by 3 desc, 4 desc, 1 asc
option (maxrecursion 32767);

但也许最好不要使用递归(参见http://www.sqlservercentral.com/Forums/Topic779830-338-1.aspx)。