月份统计sql语句,大虾们帮忙一下。。。。。。。。。

bluedreams85 2007-07-17 03:39:54
现在有一些合同,每张都有签定日期,我现在要根据用户输入年份统计出该年份每月合数。
签定日期一般格式:2004-7-15
我想要得到格式:

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


...全文
265 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
bluedreams85 2007-07-17
  • 打赏
  • 举报
回复
Haiwer(海阔天空) ( ) 信誉:138
谢谢了。
哈。。终于得到我想要结果了:)
肥胖的柠檬 2007-07-17
  • 打赏
  • 举报
回复
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 ??不会吧
昵称被占用了 2007-07-17
  • 打赏
  • 举报
回复
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
lt1129 2007-07-17
  • 打赏
  • 举报
回复
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)
bluedreams85 2007-07-17
  • 打赏
  • 举报
回复
能不能出的这样子
2004-3 0
bluedreams85 2007-07-17
  • 打赏
  • 举报
回复
结果是这样的

2004-01 4
2004-02 1
null null
..........
2004-12 16
如果该月没有出现的是null

gahade 2007-07-17
  • 打赏
  • 举报
回复
这样试一下,没测试

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
bluedreams85 2007-07-17
  • 打赏
  • 举报
回复
不知道可不可以得到这样结果,要怎么写
bluedreams85 2007-07-17
  • 打赏
  • 举报
回复
谢谢!
我还想得到如果该月没有数据就用0
就是想得到数据是12列
1到12月
如果该月没有就是0
昵称被占用了 2007-07-17
  • 打赏
  • 举报
回复
select convert(varchar(7),签定日期,120) as 月份,
count(*) as 数量
from 合同
where year(签定日期)=2004 --2004使输入的年份
group by convert(varchar(7),签定日期,120)
gahade 2007-07-17
  • 打赏
  • 举报
回复
select convert(char(7),签定日期,120) as '月份',
count(*) as '数量'
from 表
where year(签定日期)='2007'
group by convert(char(7),签定日期,120)
order by convert(char(7),签定日期,120)

34,590

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧