【问题标题】:SQL - sum operations within case when statementSQL - case when 语句中的求和操作
【发布时间】:2020-11-09 20:54:18
【问题描述】:

我需要按日期、国家/地区等汇总一些会话。该表包含每个会话的交易金额(以当地货币表示)和一个字段,其中包含交易时间的 exchange_rate 到 EUR。像这样:

amount | currency | exchange_rate | date | country 

我运行 sum(amount/exchange_rate),但是,对于大约 0.5% 的行,exchange_rate 的值为 0,因此它会引发错误“不能除以 0”。

我尝试在以下情况下运行它:

sum(case when exchange_rate = 0 then sum(amount) else sum(amount/exchange_rate) end) as volume

但显然嵌套的 sum 是不允许的。有没有人知道我如何才能得到上述逻辑上应该产生的结果,但在 case when 语句中没有嵌套的总和?

【问题讨论】:

  • 汇率为零时你想做什么?
  • @穿刺者;我想按照 GMB 的建议将 0 替换为 1

标签: mysql sql database sum case


【解决方案1】:

基本上,当它为零时,您希望将汇率视为1。你可以这样做:

sum(case when exchange_rate = 0 
         then amount 
         else amount/exchange_rate 
    end
) as volume

【讨论】:

    【解决方案2】:

    我想你想要:

    sum(case when exchange_rate = 0 then amount else amount/exchange_rate end) as volume
    

    或者少打字:

    sum(amount / coalesce(nullif(exchange_rate, 0), 1)) as volume
    

    【讨论】:

      【解决方案3】:

      假设0的汇率表明金额已经是EUR货币,您可以这样做:

      sum(amount / case when exchange_rate = 0 then 1 else exchange_rate end)
      

      【讨论】:

        猜你喜欢
        • 2016-07-08
        • 1970-01-01
        • 1970-01-01
        • 2011-08-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-30
        相关资源
        最近更新 更多