日期:2014-05-18  浏览次数:20435 次

循环语句怎么写啊?
有个月值表 月值设为m
2011 1 -1.2
2011 2 -1.2
2011 3 -.9
2011 4 -.9
2011 5 -.7
2011 6 -.8
2011 7 -1.1
2011 8 -1.0
2011 9 -1.0
2011 10 -.8
2011 11 -.3
2011 12 -.2
.....

还有个日值表 日值设为n
2011 1 1 -.7
2011 1 2 -.2
2011 1 3 -.8
2011 1 4 -.5
2011 1 5 -1.2
2011 1 6 -1.3
2011 1 7 -1.4
2011 1 8 -.8
2011 1 9 -1.2
2011 1 10 -2.1
2011 1 11 -1.4
2011 1 12 -1.2
2011 1 13 -1.6
.....

现在要每个月的日值分别减去当月的月值
例如一月份的每个n减去当月的M
n1.1-m1
n1.2-m1
n1.3-m1
n1.4-m1
n1.5-m1
....
二月份的每个n减去当月的M
n2.1-m2
n2.2-m2
n2.3-m2
n2.4-m2
n2.5-m2
....




------解决方案--------------------
假设月值表字段为:y , m, v
2011 1 -1.2
2011 2 -1.2
2011 3 -.9
2011 4 -.9
2011 5 -.7
2011 6 -.8
2011 7 -1.1
2011 8 -1.0
2011 9 -1.0
2011 10 -.8
2011 11 -.3
2011 12 -.2

假设日值表字段为:y ,m ,n ,v
2011 1 1 -.7
2011 1 2 -.2
2011 1 3 -.8
2011 1 4 -.5
2011 1 5 -1.2
2011 1 6 -1.3
2011 1 7 -1.4
2011 1 8 -.8
2011 1 9 -1.2
2011 1 10 -2.1
2011 1 11 -1.4
2011 1 12 -1.2
2011 1 13 -1.6
-------------------------

select n.y , n.m , n.n , n.v - isnull(m.v,0) 
from 日值表 n left join 月值表 m 
on n.y = m.y and n.m = m.m 

------解决方案--------------------
SQL code

--> 测试数据:[month]
if object_id('[month]') is not null drop table [month]
create table [month]([year] int,[month] int,[value] numeric(2,1))
insert [month]
select 2011,1,-1.2 union all
select 2011,2,-1.2 union all
select 2011,3,-0.9 union all
select 2011,4,-0.9 union all
select 2011,5,-0.7 union all
select 2011,6,-0.8 union all
select 2011,7,-1.1 union all
select 2011,8,-1.0 union all
select 2011,9,-1.0 union all
select 2011,10,-0.8 union all
select 2011,11,-0.3 union all
select 2011,12,-0.2
--> 测试数据:[day]
if object_id('[day]') is not null drop table [day]
create table [day]([year] int,[month] int,[value] int,[C4] numeric(2,1))
insert [day]
select 2011,1,1,-0.7 union all
select 2011,1,2,-0.2 union all
select 2011,1,3,-0.8 union all
select 2011,1,4,-0.5 union all
select 2011,1,5,-1.2 union all
select 2011,1,6,-1.3 union all
select 2011,1,7,-1.4 union all
select 2011,1,8,-0.8 union all
select 2011,1,9,-1.2 union all
select 2011,1,10,-2.1 union all
select 2011,1,11,-1.4 union all
select 2011,1,12,-1.2 union all
select 2011,1,13,-1.6


select a.[year],a.[month],a.value as [day],a.C4-a.valueb as daymonth
from (
select a.*,b.value as valueb from [day] a inner join [month] b
on a.[year]=b.[year] and a.[month]=b.[month]) a
/*
year    month    day    daymonth
2011    1    1    0.5
2011    1    2    1.0
2011    1    3    0.4
2011    1    4    0.7
2011    1    5    0.0
2011    1    6    -0.1
2011    1    7    -0.2
2011    1    8    0.4
2011    1    9    0.0
2011    1    10    -0.9
2011    1    11    -0.2
2011    1    12    0.0
2011    1    13    -0.4
*/