将CASE语句的结果保存在表中

时间:2019-04-03 15:39:22

标签: sql select

我在将CASE语句的结果作为新列保存到housing_listing表时遇到问题。我不确定如何通过添加名为佣金价格的新列来正确更新表。

CREATE TABLE housing_listing (
    transaction_id INT PRIMARY KEY,
    number_of_bedrooms INT,
    number_of_bathrooms INT,
    listing_price INT,
    listing_agent TEXT,
    listing_office TEXT,
    date_of_listing DATETIME,
    zip_code INT,
    sold BOOL
)



SELECT transaction_id,number_of_bedrooms, number_of_bathrooms,

CASE
    WHEN listing_price < 100000 THEN listing_price * 1.1
    WHEN listing_price > 100000 AND listing_price < 200000 THEN listing_price * 1.75
    WHEN listing_price > 200000 AND listing_price < 500000 THEN listing_price * 1.6
    WHEN listing_price > 500000 AND listing_price < 1000000 THEN listing_price * 1.5
    WHEN listing_price > 1000000 THEN listing_price * 1.4

END AS Commission_price
FROM housing_listing;

1 个答案:

答案 0 :(得分:0)

通用方法是使用视图:

CREATE VIEW v_housing_listing as
    SELECT transaction_id,number_of_bedrooms, number_of_bathrooms,

           (CASE WHEN listing_price < 100000 THEN listing_price * 1.1
                 WHEN listing_price > 100000 AND listing_price < 200000 THEN listing_price * 1.75
                 WHEN listing_price > 200000 AND listing_price < 500000 THEN listing_price * 1.6
                 WHEN listing_price > 500000 AND listing_price < 1000000 THEN listing_price * 1.5
                 WHEN listing_price > 1000000 THEN listing_price * 1.4
            END) AS Commission_price
    FROM housing_listing;

这不会将值放在表中;当您引用视图时,它将对其进行计算。

许多数据库还支持计算列。