我有个订单表,一个汇率表,订单表里有字段 订单号 币种 订单金额 订单日期,汇率表里有币种 汇率 生效日期
汇率表里是一行行的表述每个时段的汇率,比如  2001-2-1 EUR 8.0
                                      2002-2-1 EUR 9.0
                                      ... ...我要求订单的总额,订单日期要对应于汇率表的相应时间的汇率 
  

解决方案 »

  1.   

    select
        sum(a.订单金额*b.汇率) as 总额
    from
        订单表 a,汇率表 b 
    where
        a.币种=b.币种 and a.订单日期=b.生效日期
      

  2.   

    子陌红尘:我是这个意思:订单日期要对应于汇率表的相应时间的汇率 比如:2002-8-1 号的订单就得对应  2002-2-1   EUR   9.0 ,如果汇率表下条记录是大于2002-8-1
      

  3.   

    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.生效日期)
      

  4.   

    上面的不能运行,用这个
    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.生效日期)
      

  5.   

    select     sum(订单金额*汇率)      as     总额   
    from 订单表 a,汇率表b
    where 
    生效日期=(select max( 生效日期) from  a ,  b  where  订单日期>生效日期)这个就可以阿
      

  6.   

    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.订单日期 ))
      

  7.   

    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.生效日期 )) 
      

  8.   

    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