当日期字段更改月

时间:2015-09-25 21:49:42

标签: sql-server

我目前正在执行以下查询:

Select *, Balance = SUM(DailyReAdmits) 
OVER (ORDER BY Date_Total ROWS UNBOUNDED PRECEDING) 
From #AllReadmits

返回以下结果:

Date_Total    DailyReAdmits    Balance
2015-08-25                4          4
2015-08-26                8         12
2015-08-27                9         21
2015-08-28                3         24
2015-08-29                1         25
2015-08-30                4         29
2015-08-31                3         32
2015-09-01                5         37

但是,当新月开始时,我希望余额重新开始,看起来像这样:

Date_Total    DailyReAdmits    Balance
2015-08-25                4          4
2015-08-26                8         12
2015-08-27                9         21
2015-08-28                3         24
2015-08-29                1         25
2015-08-30                4         29
2015-08-31                3         32
2015-09-01                5          5

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:1)

我认为你想按月分区,所以试试这个:

SELECT *, Balance = SUM(DailyReAdmits) 
OVER (PARTITION BY DATEPART(MM,Date_Total) ORDER BY Date_Total ROWS UNBOUNDED PRECEDING) 
FROM #AllReadmits