2016-04-12 65 views
0

我試圖總結個別價格並使用邏輯來獲得折扣。SQL select語句,根據其他列計算列

SELECT O.OrderID, 
    if(C.IsClubMember & OrderNumber % 10 = 0, 0.5 * Sum(I.ItemPrice), Sum(I.ItemPrice)) as Price, 
    0.07*Price as Tax, Price + Tax as Total 
FROM Orders as O JOIN ItemPriceView as I 
    ON O.OrderID = I.OrderID JOIN Customer as C 
    ON O.CustomerID = C.CustomerID 
GROUP BY OrderID 

我得到一個錯誤:

Error Code: 1054. Unknown column 'Price' in 'field list' 

什麼是寫我的查詢的正確方法?

+0

您不能重用'select'子句中的別名。 –

+0

那麼我需要將整個邏輯子句複製粘貼到select的每個部分?我是否需要制定一箇中間觀點來保持價格,然後再進行稅收和總計? –

+0

您可以在select子句中複製/粘貼邏輯 –

回答

1

一個解決方案是使用子查詢計算價格,然後計算外部查詢中的稅額和總額。

這應該工作:

SELECT OrderID, Price, 0.07*Price as Tax, 1.07*Price as Total 
FROM 
(
SELECT O.OrderID as OrderID, 
    if(C.IsClubMember & OrderNumber % 10 = 0, 0.5 * Sum(I.ItemPrice),Sum(I.ItemPrice)) as Price 
FROM Orders as O JOIN ItemPriceView as I 
    ON O.OrderID = I.OrderID JOIN Customer as C 
    ON O.CustomerID = C.CustomerID 
GROUP BY OrderID 
) as sub_query