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

急求一个查询过程的解决办法,小弟对SQL一窍不通,领导急要,谢谢大家啊!
是气象部门的一个降雨评分程序,领导突然发疯明天就要要这个东西,压给小弟,失败啊,解决后可再赠送500分作为酬谢,以姓氏作担保,决不食言,请大家帮我写一下啊……共有3个表,表A是实况值,表B是预报值,表C是每天评分的结果,几个表的结构如下:

表A:实况值
SID         date             value
50136     20070212     31
50136     20070213     20
50136     20070214     15
……
表A说明:SID字段是台站编号,date是日期,value是降水量。

表B
SID         date             1     2     3     4
50136     20070211     0     0     1     2
50136     20070212     0     1     2     3
……
表B说明:SID字段是台站编号,date是预报日期,字段1、2、3、4分别代表时间步长,1代表20070211这天的后一天,即报20070212日降水量级是0;2代表后两天,即20070213,以此类推;降水量级表示如果是0就是无降水,如果是小于等于10就是1,如果是小于等于20就是2,以此类推,表A中12、13、14日的降水量所对应的量级分别是4、2、2。

表C
SID         date             Avalue     Bvalue     Span
50136     20070211     4               0               1
50136     20070211     2               0               2
……
表C说明:SID字段是台站编号,date是预报日期,这两个跟前面一样的意思,Avalue和Bvalue分别是表A和表B中相对应时间步长(Span字段)下的降水量级。如第一行表示50136这个台站在20070211日报的明天的(Span=1)量级是0,但实况是4,报的后天(Span=2)的量级是0,实况是2,以此类推。

要求做出来一个每天可以自动运行的程序,最好是利用SQL自己的脚本或者C#编写的程序,每天运行后把结果更新到表C中。

要注意的是台站不仅只有50136,大概有100多个,每一个台站都要这么做,即每个台站每天都要做它后面四天的预报结果的评分。

谢谢大家了啊!

------解决方案--------------------
没有验证,不知道对不对

insert into 表C(sid,date,avalue,bvalue,span)
select sid,
date,
(select case when value between 1 and 10 then 1
when value between 10 and 20 then 2
when value between 20 and 30 then 3
when value between 30 and 40 then 4 else 0 end
from 表A a
where cast(a.date as datetime)=dateadd(day,1,cast(b.date as datetime)) and a.sid=b.sid),
[1],
1
from 表B b
union all
select sid,
date,
(select case when value between 1 and 10 then 1
when value between 10 and 20 then 2
when value between 20 and 30 then 3
when value between 30 and 40 then 4 else 0 end
from 表A a
where cast(a.date as datetime)=dateadd(day,2,cast(b.date as datetime)) and a.sid=b.sid),
[2],
2
from 表B b
union all
select sid,
date,
(select case when value between 1 and 10 then 1
when value between 10 and 20 then 2
when value between 20 and 30 then 3
when value between 30 and 40 then 4 else 0 end
from 表A a
where cast(a.date as datetime)=dateadd(day,3,cast(b.date as datetime)) and a.sid=b.sid),
[3],
3
from 表B b
union all
select sid,
date,
(select case when value between 1 and 10 then 1
when value between 10 and 20 then 2
when value between 20 and 30 then 3
when value between 30 and 40 then 4 else 0 end
from 表A a
where cast(a.date as datetime)=dateadd(day,4,cast(b.date as datetime)) and a.sid=b.sid),
[4],
4
from 表B b
------解决方案--------------------
--创建测试环境
create table 实况值(SID int,date datetime,value int)
create table 预测值(SID int,date datetime,[1] int,[2] int,[3] int,[4] int)
--插入测试数据
insert 实况值(SID,date,value)
select '50136 ', '20070212 ', '31 ' union