所有月份取值

xucome 2008-08-05 11:20:58
T1:
Mon cCode Val
02 001 3
04 001 2
05 001 4
01 002 6
04 002 3
06 002 5

目的表:(1.把cCode生成12个月份 2.如果T1对应的月份没有Val值,就根据上月份取值)
Mon cCode Val
01 001 0
02 001 3
03 001 3
04 001 2
05 001 4
06 001 4
07 001 4
08 001 4
09 001 4
10 001 4
11 001 4
12 001 4
01 002 6
02 002 6
03 002 6
04 002 3
05 002 3
06 002 5
07 002 5
08 002 5
09 002 5
10 002 5
11 002 5
12 002 5
...全文
84 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
stromboy007 2008-08-06
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 cyc_cheng 的回复:]
学习
[/Quote]
水族杰纶 2008-08-05
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 utpcb 的回复:]
cross join 这个也可以厉害
[/Quote]
cyc_cheng 2008-08-05
  • 打赏
  • 举报
回复
学习
utpcb 2008-08-05
  • 打赏
  • 举报
回复
cross join 这个也可以厉害
utpcb 2008-08-05
  • 打赏
  • 举报
回复
用游标!
sdxiong 2008-08-05
  • 打赏
  • 举报
回复

declare @t table (Mon char(2),cCode char(3),Val int)
insert into @t
select '02','001', 3 union all
select '04','001', 2 union all
select '05','001', 4 union all
select '01','002', 6 union all
select '04','002', 3 union all
select '06','002', 5

select c.mon,a.ccode,isnull((select top 1 val from @t where ccode=a.ccode and mon<=c.mon order by mon desc),0) as val
from (select distinct ccode from @t) a
cross join (select top 12 right('0'+cast((select count(*)
from sysobjects
where id<=b.id
) as varchar(2)),2) as mon
from sysobjects b order by id
) c
order by a.ccode,c.mon

/*
mon ccode val
---- ----- -----------
01 001 0
02 001 3
03 001 3
04 001 2
05 001 4
06 001 4
07 001 4
08 001 4
09 001 4
10 001 4
11 001 4
12 001 4
01 002 6
02 002 6
03 002 6
04 002 3
05 002 3
06 002 5
07 002 5
08 002 5
09 002 5
10 002 5
11 002 5
12 002 5

(所影响的行数为 24 行)


*/
whw502 2008-08-05
  • 打赏
  • 举报
回复
我也想知道..

27,579

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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