LZ,我觉得你要是为了以后更方便查询的话,你的汇率表设计成这样(币种 汇率 日期),日期是不间断的,既汇率不变的,也添加一条汇率表的记录,这样会不会更好点呢。
以下的SQL语句也可以实现你的要求:
select 订单号,订单日期,订单金额,汇率,(订单金额*汇率) as 单笔订单金额 into #all from 订单表 a ,汇率表
where
生效日期=
(select max(生效日期) from 订单表 b , 汇率表
where
订单日期>= 生效日期 and a.订单日期 = b.订单日期 )
and a.币种=汇率表.币种
select * from #all
select sum(单笔订单金额) from #all
drop table #all
select sum(c.订单金额*c.汇率) as 总额
from 订单表 a,汇率表b
where a.币种=b.币种 and b.生效日期=(
select top 1 b.生效日期 from b where ( select * from b where b.生效日期 <=a.订单日期 order by b.生效日期 ))
上面的不能运行,用这个
select sum(c.订单金额*c.汇率) as 总额
from (select a.币种,a.订单金额,b.汇率,b.生效日期
from 订单表 a,汇率表 b
where a.币种=b.币种 and a.订单日期=b.生效日期)c
where not exists(select 1 from
(select a.币种,a.订单金额,b.汇率,b.生效日期
from 订单表 a,汇率表 b
where a.币种=b.币种 and a.订单日期=b.生效日期)d
where a.币种=d.币种 and c.生效日期<d.生效日期)
select
sum(a.订单金额*b.汇率) as 总额
from
订单表 a where not exists(select 1 from 汇率表 b
where a.币种=b.币种 and a.订单日期<b.生效日期 and not exists(select 1 from 汇率表 c where a.币种=c.币种 and b.生效日期>c.生效日期)