日期:2014-05-19  浏览次数:20786 次

月份统计sql语句,大虾们帮忙一下。。。。。。。。。
现在有一些合同,每张都有签定日期,我现在要根据用户输入年份统计出该年份每月合数。
签定日期一般格式:2004-7-15
我想要得到格式:

月份               数量
2004-1         15
2004-2         10
2004-3         13
.......
2004-12         20




------解决方案--------------------
select convert(char(7),签定日期,120) as '月份 ',
count(*) as '数量 '
from 表
where year(签定日期)= '2007 '
group by convert(char(7),签定日期,120)
order by convert(char(7),签定日期,120)
------解决方案--------------------
select convert(varchar(7),签定日期,120) as 月份,
count(*) as 数量
from 合同
where year(签定日期)=2004 --2004使输入的年份
group by convert(varchar(7),签定日期,120)
------解决方案--------------------
这样试一下,没测试

declare @year int
set @year = 2004
select top 12 id=identity(int,1,1),dt=cast( ' ' as char(7)) into #t from sysobjects

update #t
set dt=rtrim(@year)+ '- '+right( '0 '+rtrim(id),2)

select t.月份,t.数量 from #t
left join (select convert(char(7),签定日期,120) as '月份 ',
count(*) as '数量 '
from 表
where year(签定日期)=@year
group by convert(char(7),签定日期,120))t on t.月份 = #t.dt

drop table #t
------解决方案--------------------
select convert(char(7),签定日期,120) as '月份 ',
isnull(count(*),0) as '数量 '
from 表
where year(签定日期)= '2007 '
group by convert(char(7),签定日期,120)
order by convert(char(7),签定日期,120)

------解决方案--------------------
select top 12 id=identity(int,1,1) into #t from sysobjects

select '2004- '+right( '0 '+cast(t.id as varchar),2) as 月份,
isnull(x.数量,0) as 数量
from #t t left join (
select convert(varchar(7),签定日期,120) as 月份,
count(*) as 数量
from 合同
where year(签定日期)=2004 --2004使输入的年份
group by convert(varchar(7),签定日期,120)
) as x
on '2004- '+right( '0 '+cast(t.id as varchar),2)=x.月份

drop table #t
------解决方案--------------------
gahade(与君共勉) ( ) 信誉:100 2007-07-17 16:40:03 得分: 0


这样试一下,没测试

declare @year int
set @year = 2004
select top 12 id=identity(int,1,1),dt=cast( ' ' as char(7)) into #t from sysobjects

update #t
set dt=rtrim(@year)+ '- '+right( '0 '+rtrim(id),2)

select t.月份,isnull(t.数量,0) 数量 from #t -----在这改一下
left join (select convert(char(7),签定日期,120) as '月份 ',
count(*) as '数量 '
from 表
where year(签定日期)=@year
group by convert(char(7),签定日期,120))t on t.月份 = #t.dt

drop table #t


--------------
2004-01 4
2004-02 1
null null

月会出现 unll ??不会吧