有数据表TB内容如下
[自增ID值] [姓名] [加入日期]ID Name Indate
1 张三 2012-1-02 00:00:00
2 张三 2012-2-02 00:00:00
3 张三 2012-3-02 00:00:00
4 张三 2012-4-02 00:00:00
5 张三 2012-5-02 00:00:00
6 张三 2012-5-02 00:00:00
7 张三 2012-7-02 00:00:00
8 张三 2012-8-02 00:00:00
9 张三 2012-9-02 00:00:00
10 张三 2013-1-02 00:00:00求一存储过程根据输入的年份值如输入2012 希望得到结果如下
月份 新加人数1月 1
2月 1
3月 1
4月 1
5月 2
6月 0
7月 1
8月 1
9月 1
10月 0
11月 0
12月 0
sql存储
[自增ID值] [姓名] [加入日期]ID Name Indate
1 张三 2012-1-02 00:00:00
2 张三 2012-2-02 00:00:00
3 张三 2012-3-02 00:00:00
4 张三 2012-4-02 00:00:00
5 张三 2012-5-02 00:00:00
6 张三 2012-5-02 00:00:00
7 张三 2012-7-02 00:00:00
8 张三 2012-8-02 00:00:00
9 张三 2012-9-02 00:00:00
10 张三 2013-1-02 00:00:00求一存储过程根据输入的年份值如输入2012 希望得到结果如下
月份 新加人数1月 1
2月 1
3月 1
4月 1
5月 2
6月 0
7月 1
8月 1
9月 1
10月 0
11月 0
12月 0
sql存储
set @s_time='2012-01-01'
set @e_time=convert(varchar,dateadd(y,1,@s_time),23)
;with cte as(
select dateadd(m,number,@s_time) time
from master..spt_values where type='P' and number<12
),cte1 as
(select convert(varchar(7),time,23) t,count(1) c
from tb where time>@s_time and time<@e_time group by convert(varchar(7),time,23)
),cte2 as
(select a.time as 月份,isnull(t.c,0) as 新增数量 from cte a left join cte1 b on a.time=b.t where time<@e_time)
select * from cte2
with tb(
ID , Name , Indate)as (
select 1, '张三', '2012-1-02 00:00:00' union all
select 2, '张三', '2012-2-02 00:00:00' union all
select 3, '张三', '2012-3-02 00:00:00' union all
select 4, '张三', '2012-4-02 00:00:00' union all
select 5, '张三', '2012-5-02 00:00:00' union all
select 6, '张三', '2012-5-02 00:00:00' union all
select 7, '张三', '2012-7-02 00:00:00' union all
select 8, '张三', '2012-8-02 00:00:00' union all
select 9, '张三', '2012-9-02 00:00:00' union all
select 10, '张三', '2013-1-02 00:00:00')
select number,isnull(b,0) from (select number from master..spt_values
where type='p' and number between 1 and 12)a
left join (select month(indate)a,count(1)b from tb
where year(indate)=2012 group by month(indate))b
on number=a
给year(indate)定义个参数就行...
master..spt_values 你看看这个表就知道了..用这个表左链接你的表
if object_id('bc','u') is not null
drop table bc
create table bc(ID int identity(1,1),
Name varchar(20),
Indate datetime)
insert into bc
select '张三', '2012-1-02 00:00:00' union all
select '张三', '2012-2-02 00:00:00' union all
select '张三', '2012-3-02 00:00:00' union all
select '张三', '2012-4-02 00:00:00' union all
select '张三', '2012-5-02 00:00:00' union all
select '张三', '2012-5-02 00:00:00' union all
select '张三', '2012-7-02 00:00:00' union all
select '张三', '2012-8-02 00:00:00' union all
select '张三', '2012-9-02 00:00:00' union all
select '张三', '2013-1-02 00:00:00'go
if object_id('mp','p') is not null
drop procedure mp
go
create procedure mp
@year int
as
select number,isnull(d,0) from (select number from master..spt_values
where type='p' and number between 1 and 12)a
left join (select month(indate)c,count(1)d from bc
where year(indate)=@year group by month(indate))b
on number=c
go
exec mp 2012借用了3楼的查询语句