首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

依据输入的年份显示全年的按月的统计

2013-02-25 
根据输入的年份显示全年的按月的统计有数据表TB内容如下[自增ID值][姓名][加入日期]IDNameIndate1张三2012

根据输入的年份显示全年的按月的统计
有数据表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 存储
[解决办法]

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)定义个参数就行...

[解决办法]
use xuanya
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楼的查询语句

热点排行