[英]SQL select statement that creates calculated column, then uses calculated column for another calculated column
我需要為另一列使用計算列。
這是我到目前為止所擁有的:
SELECT item_name,
list_price,
discount_percentage,
list_price * discount_percentage AS discount_amount,
list_price * discount_percentage - discount_amount AS discount_price,
FROM items
ORDER BY discount_price DESC
由於我試圖使用計算列來創建另一個計算列,所以這不正確
我想為此使用 select 語句,所以我沒有研究任何其他方法。 有沒有人看到任何明顯的錯誤?
您需要一個表表達式來“命名”您創建的表達式。 然后就可以在外層查詢中使用了,如下圖:
For example:
select
*,
list_price * discount_percentage - discount_amount AS discount_price,
from (
SELECT item_name,
list_price,
discount_percentage,
list_price * discount_percentage AS discount_amount
FROM items
) x
ORDER BY discount_price DESC
在MySQL中,可以使用行內變量來完成。 首先,您可以使用 @ 聲明一個變量並根據:= 進行分配,這就是分配的名稱結果列。 然后,@variable 可用於后續專欄 select。要聲明變量,只需在 FROM 子句中將其設置為別名,然后照常繼續。
SELECT item_name,
list_price,
discount_percentage,
-- assuming the discount percentage of 10% would be .10, not 10.
-- if 10% = 10.0, then do ( discount_percentage / 100.0 )
@myDiscount := list_price * discount_percentage AS discount_amount,
list_price - @myDiscount AS discount_price
FROM
items,
( select @myDiscount := 0.0 ) sqlvars
ORDER BY
discount_price DESC
由於 SQLVars 別名只會返回 1 條記錄,我們可以只使用逗號分隔的附加表,不需要 JOIN 子句。 聲明變量。
然后,在 COLUMNS 表中,您可以看到它是如何首先通過計算折扣金額並分配給 @myDiscount VARIABLE 來計算的,但存儲到最終結果列 DISCOUNT_AMOUNT 中。 然后,可以將 VARIABLE 用作從標價中直接減去折扣價。
不需要 select 來自 select 結果
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.