SQL查询 - 使用if条件和连接更新列

时间:2017-03-28 12:11:18

标签: sql if-statement join

请求您帮助编写更新查询,并加入2个表和if条件。

此处将金额转换为美元。有2个表。 A - 金额和原始货币,B-与汇率,货币和类型。 应使用以下条件获取Exch_rate值,其中b。[Rate Type] =' Actual'。如果特定货币没有b的相应行。[费率类型] ='实际',则应考虑具有值b的行的exch_rate。[费率类型] =' NA&# 39;

这是我到目前为止所得到的。此查询只能更新表B中具有相应行的项目,其中[费率类型] ='实际'。我不知道如何检查相应的行是否存在并相应更新

update a
    set [USD_AMT]=a.[Amt] *  b.[Exch Rate]
    from [dbo].a
    inner join [dbo].b
on
    a.[Currency]=b.[From Cur]
    and month(a.month)=month(b.[Eff Date])

where
    b.[To Cur]='USD' and
    b.[Rate Type]='Actual' 

表A:

Amt |货币|月| USD_AMT

100 | GBP | Jan

200 | ISD | 二月

表B:

来自cur |要|费率类型|月| Exch_Rate

GBP USD实际1月0.16

GBP USD NA Jan 0.18

ISD USD NA 2月65日

请帮忙。

1 个答案:

答案 0 :(得分:1)

  

如果特定货币没有相应的行   b。[Rate Type] ='Actual',那么它应该考虑exch_rate of row   值b。[费率类型] ='NA'。

标准方法使用两个left join s,一个用于首选值,另一个用于默认值:

update a
    set [USD_AMT] = a.[Amt] *  coalesce(b.[Exch Rate], bdef.[Exch Rate])
    from [dbo].a left join
         [dbo].b
         on a.[Currency] = b.[From Cur] and
            month(a.month) = month(b.[Eff Date]) and
            b.[To Cur] = 'USD' and
            b.[Rate Type] = 'Actual' left join
         [dbo].b bdef
         on a.[Currency] = bdef.[From Cur] and
            month(a.month) = month(bdef.[Eff Date]) and
            -- b.[To Cur] = 'USD' and  -- I don't know if this is needed
            b.[Rate Type] = 'N/A';