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

时间:2010-05-19 14:04:10

标签: sql

我打算为包含以下表格结构的表格获取报告:

ID              RequestDate
-----------------------------
1               2010/01/01
2               2010/02/14
3               2010/03/20
4               2010/01/07
5               2009/03/31

我希望结果如下: 我

D_Count    RequestDate               Sum
-----------------------------------------
2               2010/01              2
1               2010/02              3
2               2010/03              5

请帮助。

1 个答案:

答案 0 :(得分:5)

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

select
   count(*), datePart("yy", requestDate) + "/" + datePart("mm", requestDate)
from table1
group by 
datePart("yy", requestDate), datePart("mm", requestDate)

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

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