多个案例陈述无法解决

时间:2016-04-28 23:50:49

标签: sql postgresql nested case

我试图在我的代码中添加以下逻辑(它很大并且没有这个工作,所以下面的代码必须有问题)但是我收到了错误。我怀疑END有问题,但逻辑上认为所有3都应该在最后,所以我不确定

case
    when t0."Final Sale Price" is null
      then null
    else case
      when t1."Fee" is not null
      and t0."Final Sale Price" >= t1."Guaranteed Price"
        then t1."Fee"
      else case
        when t1."Fee" is not null
        and t0."Final Sale Price" <= t1."Guaranteed Price"
          then t1."Fee" - (t1."Guaranteed Price" - t0."Final Sale Price")
        else case
          when t0."Final Sale Price" < t1."Guaranteed Price"
            then t0."Final Sale Price" - t1."Guaranteed Price"
          else(
            (
              (t0."Final Sale Price" - t1."Guaranteed Price") * (100 - t1."Seller Upside %")
            )
            / 100
          )
        end
      end
    end as "Actual Revenue"

2 个答案:

答案 0 :(得分:1)

通常不需要嵌套case语句:

select (case when t0."Final Sale Price" is null
             then null
             when t1."Fee" is not null and t0."Final Sale Price" >= t1."Guaranteed Price"
             then t1."Fee"
             when t1."Fee" is not null and t0."Final Sale Price" <= t1."Guaranteed Price"
             then t1."Fee" - (t1."Guaranteed Price" - t0."Final Sale Price")
             when t0."Final Sale Price" < t1."Guaranteed Price"
             then t0."Final Sale Price" - t1."Guaranteed Price"
             else (t0."Final Sale Price" - t1."Guaranteed Price") * (100 - t1."Seller Upside %") / 100
          )
       end) as "Actual Revenue"

答案 1 :(得分:0)

case 
when t0."Final Sale Price" is null then null
when t1."Fee" is not null then 
     case when t0."Final Sale Price" >= t1."Guaranteed Price" then t1."Fee" 
          when t0."Final Sale Price" < t1."Guaranteed Price" then t1."Fee" - (t1."Guaranteed Price" - t0."Final Sale Price")
     end
when t0."Final Sale Price" < t1."Guaranteed Price" then t0."Final Sale Price" - t1."Guaranteed Price"
else ((t0."Final Sale Price" - t1."Guaranteed Price") * (100 - t1."Seller Upside %")) / 100
end as "Actual Revenue"

表达式可以如上简化。

另请注意,问题有两个条件,

t0."Final Sale Price" >= t1."Guaranteed Price"

t0."Final Sale Price" <= t1."Guaranteed Price"

最终销售价格=两种条件下的保证价格。如果第一个结果为真,则第二个条件在它们相等时不会被评估。根据您对=表达式的期望输出,确保case仅指定一次。