【问题标题】:SQL query - To update a column with if condition and joinSQL 查询 - 使用 if 条件更新列并加入
【发布时间】:2017-03-28 12:11:18
【问题描述】:

请求您帮助编写连接 2 个表和 if 条件的更新查询。

在此处将金额转换为美元。有2张桌子。 A - 包含金额和原始货币,B - 包含汇率、货币和类型。 Exch_rate 值应在以下条件下获取,其中 b.[Rate Type]='Actual'。如果某个特定货币没有对应的 b.[Rate Type]='Actual' 行,则应考虑值为 b.[Rate Type]='NA' 的行的 exch_rate

这是我到目前为止所得到的。此查询只能更新表 B 中 [Rate Type]='Actual' 中具有相应行的项目。我不确定如何检查相应的行是否存在并相应更新

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 | 英镑 | 一月

200 | 内政部 | 二月

表 B:

来自 cur |治疗|费率类型 |月 | Exch_Rate

英镑美元实际 1 月 0.16 日

英镑美元北美 1 月 0.18 日

ISD USD NA 2 月 65 日

请帮忙。

【问题讨论】:

  • 标记您正在使用的 dbms。该更新声明尝试是特定于产品的。

标签: sql if-statement join


【解决方案1】:

如果特定货币没有对应的行 b.[Rate Type]='Actual',那么应该考虑exch_rate of row with 值 b.[Rate Type]='NA'。

标准方法使用两个left joins,一个为首选值,一个为默认值:

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';

【讨论】:

  • 天才!非常感谢您的快速响应并提供解决方案:)
猜你喜欢
  • 1970-01-01
  • 2012-04-21
  • 1970-01-01
  • 2016-02-07
  • 1970-01-01
  • 2020-10-24
  • 1970-01-01
  • 2021-08-31
  • 1970-01-01
相关资源
最近更新 更多