创建一个别名虚拟列,其中包含两列中任意一列的值

时间:2015-07-30 13:18:09

标签: mysql

请参阅下面的SQL查询:

SELECT * 
FROM
    (SELECT 
         h.hotel_id AS id,h.hotel_city AS city,h.hotel_name AS hotelname,
         h.hotel_star AS hotelcat, hwd.double_spl_rate, hwd.third_party_rate,
         hwd.extra_bed_spl_rate, hwd.meal_plan_spl,
         hwd.third_party_extra_bed, hwd.third_party_meal_plan,
         hwd.room_category, hrd.hotel_rate_from, hrd.hotel_rate_to 
     FROM 
         hotels_list AS h 
     INNER JOIN 
         hotel_rate_detail AS hrd ON h.hotel_id = hrd.hotels_id
     INNER JOIN 
         hotel_week_days AS hwd ON hrd.hotel_id = hwd.h_id
     WHERE 
         (('2015-07-31' BETWEEN hrd.hotel_rate_from AND hrd.hotel_rate_to)
          OR 
          ('2015-08-01' BETWEEN hrd.hotel_rate_from AND hrd.hotel_rate_to)
         )
         AND (h.hotel_city = '1')
         AND (hwd.double_spl_rate != 0 OR hwd.third_party_rate != 0)
         AND (h.hotel_star = '4')
     ORDER BY 
         hwd.double_spl_rate, hwd.third_party_rate ASC) AS result_table 
GROUP BY 
    result_table.id
ORDER BY 
    result_table.double_spl_rate, result_table.third_party_rate ASC
LIMIT 0,5;

OUTPUT附于下方:

enter image description here

在上面的输出中,有两列double_spl_ratethird_party_rate,它们可以是0或大于零的值。

如何创建仅包含大于零的值的虚拟列别名。我们假设列为final_rate,其中包含的值为

id   | final_rate
533  |   3776
9228 |   3000

1 个答案:

答案 0 :(得分:1)

是的,您可以这样做:

select 
  id, 
  case 
    when coalesce(double_spl_rate,0) = 0 
    then third_party_rate 
    else double_spl_rate 
  end as final_rate
from table

coalesce运算符会将double_spl_rate设置为0(如果它为空),如果third_party_rate为0,则case表达式将返回double_spl_rate

如果double_spl_rate不能为空,则可以跳过coalesce部分。

请注意,上面的代码总是更喜欢double_spl_rate中的值,如果两个值都大于0,则忽略其他值。如果您不想这样,可以将case表达式中的逻辑扩展到account为此,并返回值的总和。或者你可以在所有情况下只返回third_party_rate + double_spl_rate