2010-05-19 122 views
-3

我打算得到一個表格的報告具有以下表結構:T-SQL查詢來獲取SUM(COUNT())

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 

請幫忙。

+0

你的意思是T-SQL? 'RequestDate'是一個'varchar'或'datetime'? – 2010-05-19 14:08:35

+0

你在總結什麼? – 2010-05-19 14:09:28

+0

RequestDate是日期時間和我正在求和D_Count – Ashish 2010-05-19 14:11:58

回答

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 
+0

不。這不會解決查詢 – Ashish 2010-05-19 14:18:35

+0

+1:由於缺乏信息,這是最好的可以完成 – RedFilter 2010-05-19 14:26:53

+0

這解決了我的查詢。 – Ashish 2010-05-19 15:20:06