我正在使用您提供到#tbl 中的数据,然后使用每个月和年的计数制作一个#tbl1。之后,我将#tbl1 与#tbl 本身结合在一起,条件是小于等于年和月。
select * into #tbl from
(
select 'TN128757' accNO, CAST('2013-07-21' AS date) HO_DATE
union all select 'TN126822', cast('2013-05-16' as date)
union all select 'TN130058', cast('2013-10-11' as date)
union all select 'TN130375', cast('2013-10-30' as date)
union all select 'TN128396', cast('2013-06-20' as date)
union all select 'TN129800', cast('2013-10-22' as date)
union all select 'TN127399', cast('2013-08-25' as date)
) A
select * into #tbl1 from (
select COUNT(*) Cnt, CAST(DATEPART(Year,HO_DATE) as varchar) + '-' + CAST(DATEPART(MONTH,HO_DATE) as varchar) MONTHYEAR, DATEPART(Year,HO_DATE) YEAR ,DATEPART(MONTH,HO_DATE) MONTH
from #tbl
group by DATEPART(Year,HO_DATE),DATEPART(MONTH,HO_DATE), CAST(DATEPART(Year,HO_DATE) as varchar) + '-' + CAST(DATEPART(MONTH,HO_DATE) as varchar)
) A
select * from #tbl1
select A.MONTHYEAR, A.YEAR, A.MONTH, SUM(B.Cnt) from #tbl1 A
inner join #tbl1 B ON A.YEAR>=B.YEAR and A.MONTH>=B.MONTH
GROUP BY A.MONTHYEAR, A.YEAR,A.MONTH
order by A.YEAR,A.MONTH
drop table #tbl;
drop table #tbl1;
希望这对你有用。相应地给出表名,如果您有任何问题,请告诉我。
干杯:) ......