原始SQL查询

时间:2018-03-19 05:38:14

标签: mysql ruby-on-rails-5

我有一个SQL查询,它已经使用IF()函数来检查返回相应表达式的某些条件。我必须在IF()中添加另一个条件(将是另一个'和'),这将影响两个表达式的属性。查询是,

select 
  #{booking_variable}.travel_id as operator_id,
  round(sum(#{ticket_variable}.customer_commission), 2) as commission,
  IF(
    (#{booking_variable}.is_online = #{AdminType::YES} 
      and #{booking_variable}.is_ts_payment = #{AdminType::YES}),
    round(sum(-#{ticket_variable}.customer_commission
      - #{ticket_variable}.convenience_charge_amount
      + #{ticket_variable}.our_convenience_charge_amount), 2),
    round(sum(#{ticket_variable}.adult_fare 
      - #{ticket_variable}.customer_commission
      + #{ticket_variable}.service_tax_amount
      + #{ticket_variable}.our_convenience_charge_amount 
      - #{ticket_variable}.offer_discount), 2)
  ) as amount_to_be_paid,
  round(sum(#{booking_variable}.total_fare)) as total_fare,
  0 as cancel_fare,
  round(sum(#{ticket_variable}.adult_fare 
      + #{ticket_variable}.service_tax_amount
      - #{ticket_variable}.offer_discount )) as net_amount,
  #{booking_variable}.travel_name as operator_name,
  ROUND(sum(#{ticket_variable}.service_tax_amount), 2) as total_service_tax,
  ROUND(sum(#{ticket_variable}.convenience_charge_amount), 2) as total_convenience_charge_amount,
  ROUND(sum(#{ticket_variable}.our_convenience_charge_amount), 2) as total_our_convenience_charge_amount,
  0 as cancelled_convenience_charge_amount,
  (select users.branch_id from users where id=#{ticket_variable}.booked_by) as travel_branch_id
from #{booking_variable} use index(index_#{booking_variable}_travel_date), 
  #{ticket_variable}
where #{conditions1[0]} 
group by travel_branch_id, operator_id

这里,在IF()表达式中,我必须检查另一个变量的值。如果值为true,则查询应按原样运行,否则,#{ticket_variable}.convenience_charge_amount + #{ticket_variable}.our_convenience_charge_amount#{ticket_variable}.our_convenience_charge_amount的值将被视为0。 任何帮助赞赏。

1 个答案:

答案 0 :(得分:0)

您可以嵌套IF()个表达式。

如果您需要将部分计算作为条件,则可以使用IF()

...
  IF(
    (#{booking_variable}.is_online = #{AdminType::YES} 
      and #{booking_variable}.is_ts_payment = #{AdminType::YES}),
    round(sum(-#{ticket_variable}.customer_commission
      - IF((...some other condition...),
        #{ticket_variable}.convenience_charge_amount
        + #{ticket_variable}.our_convenience_charge_amount,
        0)
      ), 2),
...