【问题标题】:Calculation in query based on the condition基于条件的查询计算
【发布时间】:2016-04-12 03:52:27
【问题描述】:

我在 oracle 中有一个包,其中包含几个程序,在其中一个程序中,我需要根据特定条件计算一些费用,如下所示:

if X_flag = 1 then fee = (.5 * orders.total_count) + (.3 * orders.total_amount) else fee = (.7 * orders.total_count) + (.4 * orders.total_amount)

那么,有什么更好的方法呢?


我需要在其上添加此计算的过程:

procedure informatonRPT ( 
p_customerID in number, 
p_orderID in number)
as
begin 
    select     
        cusromers.costomerId,
        cusromers.costomerName,
        cusromers.coustomerPhone,
        orders.price 

    from       cusromers 
    inner join orders
            on cusromers.orderId = orders.orderID     
    when 
        p_customerID is null or p_customerID = cusromers.costomerId 
        and p_orderID is null or p_orderID = orders.orderID ;

end informatonRPT;

客户表列:

  • 客户ID
  • 客户姓名
  • 客户电话
  • 有序ID

订单表列:

  • 订单号
  • 价格
  • total_Amount
  • total_count

请注意: 数据库中不存在费用列,我必须在查询中计算它

【问题讨论】:

  • 我认为您需要添加更多信息,因为首先您会说 X_flag feetabletable_count 但您的程序没有这些信息。那么这些字段定义在哪里呢?
  • 你在哪里得到X_flag
  • 来自数据库中的另一个表,我在该过程中没有使用它
  • 你检查我的答案了吗?
  • 我必须在同一过程中将其添加为子查询吗?还是作为包中的单独函数?

标签: oracle stored-procedures package conditional


【解决方案1】:

我再次不确定,因为您没有提供足够的信息,但您需要使用 CASE 表达式

SELECT C.costomerId,
       C.costomerName,
       C.coustomerPhone,
       O.price,
       CASE X_flag 
          WHEN 1 THEN (.5 * O.total_count) + (.3 * O.total_amount) 
          ELSE 7 * O.total_count) + (.4 * O.total_amount)
       END as fee
FROM cusromers C
join orders O
  on C.orderId = O.orderID     

oracle CASE 文档

【讨论】:

  • 检查我的更新,现在可能会更有意义。还是不知道X_flag来自哪里
  • 如果解决了你的问题,记得接受正确的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多