请参阅下面的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附于下方:
在上面的输出中,有两列double_spl_rate
和third_party_rate
,它们可以是0或大于零的值。
如何创建仅包含大于零的值的虚拟列别名。我们假设列为final_rate
,其中包含的值为
id | final_rate
533 | 3776
9228 | 3000
答案 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
。