SQL Server从星期一开始按星期汇总

时间:2018-02-07 17:10:46

标签: sql sql-server tsql

我需要从星期一开始按周汇总收入字段。我的数据如下:

Date        Rev
+----------+--------
 4/10/2017     5
 4/11/2017     6
 4/12/2017     7
 4/13/2017     8
 4/17/2017     9
 4/19/2017     12

我希望数据能够显示一周的第一天以及该周的摘要,如:

Date        Rev
+----------+--------
 4/10/2017     26
 4/17/2017     21

我怎么能做到这一点?

2 个答案:

答案 0 :(得分:1)

<i class="fa fas fa-user"></i>
<i class="fa far fa-user-secret"></i>
<i class="fa fab fa-github-square"></i>
  

SQLFiddle

这会映射到您的示例数据。它起作用,因为第0天(1/1/1900)恰好落在星期一。如果您需要使用星期日或星期二作为星期开始,您将相应地调整输入日期和偏移量。

答案 1 :(得分:0)

这里有一个例子,您可以使用datepart函数轻松获得结果:

create table #temp
([Date] datetime, Rev int)

insert into #temp values ('2010-01-01',10)
insert into #temp values ('2010-01-02',20)
insert into #temp values ('2010-01-07',60)
insert into #temp values ('2010-01-09',50)

SELECT DATEPART (wk, [Date]) AS Week, Sum(Rev) AS TotalRev
FROM #temp
Group By DATEPART (wk, [Date]);

编辑: 如果您坚持使用第一个日期值而不是周数,那么这是您的替代解决方案:

;with cte (firstdateofweek,weekno) as
(
   select min([Date]) as firstdateofweek ,DATEPART (wk, [Date]) weekno
   from #temp
   group by DATEPART (wk, [Date])
)
SELECT cte.firstdateofweek AS Week,sum(Rev) AS Sales
FROM #temp
INNER JOIN cte on DATEPART(wk, [Date]) = cte.weekno
Group By cte.firstdateofweek