计算每月的条目,但前几个月的SQL总数

时间:2013-10-21 09:06:52

标签: sql sql-server date

我需要每月获得一个帐户总数,但在下个月它应该包含之前的总数。表中有2列用于AccNO,另一列用于日期。我们按月和日计算每月的总数。

accNO           HO_DATE
---------------------------
TN128757    2013-07-21

TN126822    2013-05-16

TN130058    2013-10-11

TN130375    2013-10-30

TN128396    2013-06-20

TN129800    2013-10-22

TN127399    2013-08-25

所以最后总计将是

2013/05 = 1

2013/06 = 2

2013/07 = 3

2013/08 = 4

2013/09 = 4

2013/10 = 7

那么我将如何分组或如何将其包含在where子句中。我正在使用MSSQL 2012

感谢

1 个答案:

答案 0 :(得分:0)

我正在使用你提供给#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;

希望这适合你。相应地提供表格名称,如果您有任何问题,请告诉我。

干杯:) ......