如何根据 相同的执行人ID 来统计每个月有多少条数据 特别注明:如何七月份没有产生数据则用0代替。格式为:
例如其中的表字段为:(userID 标识列,createDate_Time 为数据产生的时间 ExecuteID 为数据创建人ID) 现在要根据Execute来查找所创建人ID的每个月(月份期间不产生数据的月份用0代替)数据条数
ID createDate_Time ExecuteID
1 ..... 2
年月日 产生的数据条
2011年01月 0
2011年02月 5
例如其中的表字段为:(userID 标识列,createDate_Time 为数据产生的时间 ExecuteID 为数据创建人ID) 现在要根据Execute来查找所创建人ID的每个月(月份期间不产生数据的月份用0代替)数据条数
ID createDate_Time ExecuteID
1 ..... 2
年月日 产生的数据条
2011年01月 0
2011年02月 5
然后left (聚合后的结果)
2008年12月
2009年1月
……
2009年9月
declare @t datetime
set @t='20081102'
select result=convert(varchar(7),dif,120) from
(
select dif=dateadd(month,number,@t) from master..spt_values where type='p'
) m
where dif<getdate()/*
result
-------
2008-11
2008-12
2009-01
2009-02
2009-03
2009-04
2009-05
2009-06
2009-07
2009-08
2009-09(11 行受影响)
*/
insert into tb select 1,'2011-01-15',1
insert into tb select 2,'2011-05-21',5
go
select a.number 月份,c.executeid 执行者,sum(case when b.createdate_time is not null then 1 else 0 end)次数
from master..spt_values a full join (select distinct executeid from tb)c on 1=1
left join tb b on a.number=month(b.createdate_time)
where a.type='p' and a.number between 1 and 12
group by a.number,c.executeid
/*
月份 执行者 次数
----------- ----------- -----------
1 1 1
2 1 0
3 1 0
4 1 0
5 1 1
6 1 0
7 1 0
8 1 0
9 1 0
10 1 0
11 1 0
12 1 0
1 5 1
2 5 0
3 5 0
4 5 0
5 5 1
6 5 0
7 5 0
8 5 0
9 5 0
10 5 0
11 5 0
12 5 0(24 行受影响)*/
go
drop table tb
SQL codecreate table tb(id int,createdate_time nvarchar(20),executeid int)
insert into tb select 1,'2011-01-15',1
insert into tb select 2,'2011-05-21',5
go
select a.number 月份,c.executeid 执行者,s……
[/Quote当然是datetime啦