SQL - 创建此嵌套Select案例查询的更好方法

时间:2017-07-19 05:05:00

标签: sql performance case

我必须根据特定条件检索金额总和。有2个表

1. Stocks table
2. Payments table

这是要求

"Select all Stocks from Stocks table that has 
 RecordID is 9 
 If amount in Payment table is not null   
    ADD amount TO Stockamount
 else 
    find the greater number between Amt1 , Amt2, balAmt in Stocks table
    Multiply the number with 0.04  , 
    ADD this number to  Stockamount
 END-IF"
 Return Stockamount

注意:所有字段中的金额值都存储为字符串。它们需要在乘法之前转换为int。 此外,amount字段可以为null,这在我对字段进行类型转换时会出错。我试图在case语句中检查空值。

我已经编写了这样的选择案例陈述

select SUM("Amount") as "StockAmount" 
from (
    select 
        case 
            when ltrim(rtrim(b.c_amount)) <> '' 
                then cast(b.c_amount as int) 
            when ltrim(rtrim(a.c_balamt)) = '' and cast(a.c_amt1 as int)>=cast(a.c_amt2 as int) 
                then cast(a.c_amt1 as int)*0.04 
            when ltrim(rtrim(a.c_balamt)) = '' and cast(a.c_amt2 as int)>cast(a.c_amt1 as int) 
                then cast(a.c_amt2 as int)*0.04 
            when cast(a.c_amt1 as int)>=cast(a.c_balamt as int) and cast(a.c_amt1 as int)>=cast(a.c_amt2 as int) 
                then cast(a.c_amt1 as int)*0.04 
            when cast(a.c_amt2 as int)>=cast(a.c_balamt as int) and cast(a.c_amt2 as int)>cast(a.c_amt1 as int) 
                then cast(a.c_amt2 as int)*0.04 
            when cast(a.c_balamt as int)>=cast(a.c_amt1 as int) and cast(a.c_amt2 as int) <=cast(a.c_balamt as int) 
                then cast(a.c_balamt as int)*0.04 
            else 0 
        end as "Amount" 
    from STOCKS_TABLE a,
        PAYMENTS_TABLE b
    where a.c_recordid = 9 
        and substr(a.t_tradeline_id,3)=b.parent_id 
)

有没有更好的方法来编写此查询?

0 个答案:

没有答案