Step1: 首先得到每月的记录

	WITH TABLE monthlydata AS 
	( 
	         SELECT   sum(xxx) AS totalcases, 
	                  id, 
	                  month(date) AS [month] 
	         FROM     yourtable 
	         GROUP BY id, 
	                  month(date) 
	)

Step2: 然后进行Sum up

对上方表进行操作:

  • 若部分month的没有产值而显示为0的话
    • 不需要额外操作
  • 若部分month的没有产值而显示为NULL的话
    • 进行一下判断将其变为0
  • 若部分month的没有产值导致上方表结果中只有一年中部分月份的数据
    • 额外JOIN一张表变量,这张表有12行数据分别是1-12
	declare @monthIndex as table 
	(
	    [month] INT
	)
	
	DECLARE @hid INT;
	SET @hid=1;
	WHILE @hid <= 12
	BEGIN 
	    INSERT INTO @monthIndex VALUES(@hid)
	    SET @hid = @hid + 1;
	END

然后进行判断

	select 
	    i.siteid,
	    mindex.month,
	    sum(totalcases ) as SumUpRecCases
	
	from MonthlyData, @monthIndex mindex
	where i.month <= mindex.month
	group by i.siteid, mindex.month

最终会显示多行

参考文献

generate-year-to-date-by-month-report-in-sql