获取SUM的T-SQL查询(COUNT())

Ash*_*ish -3 sql

我打算获得一个包含以下表结构的表的报告:

ID              RequestDate
-----------------------------
1               2010/01/01
2               2010/02/14
3               2010/03/20
4               2010/01/07
5               2009/03/31
Run Code Online (Sandbox Code Playgroud)

我希望结果为:I

D_Count    RequestDate               Sum
-----------------------------------------
2               2010/01              2
1               2010/02              3
2               2010/03              5
Run Code Online (Sandbox Code Playgroud)

请帮忙.

Avi*_*tus 5

您只需按表格的年份和月份日期分组即可获得每月和每年的计数:

select
   count(*), datePart("yy", requestDate) + "/" + datePart("mm", requestDate)
from table1
group by 
datePart("yy", requestDate), datePart("mm", requestDate)
Run Code Online (Sandbox Code Playgroud)

要获得这些的总和,您必须拥有临时表,然后使用运行总计更新该临时表总和列.

create table #temp ( rowID identity(1,1) int, dateCount int, yearMonth varchar(50), runningTotal int)

insert into #temp ( dateCount, yearMonth, runningTotal ) 
    select
       count(*), datePart("yy", requestDate) + "/" + datePart("mm", requestDate)
    from table1
    group by 
    datePart("yy", requestDate), datePart("mm", requestDate)

update #temp set runningTotal = (select sum(dateCount) from #temp a where a.rowID < #temp.rowID)

select * from #temp 

drop table #temp 
Run Code Online (Sandbox Code Playgroud)