SQL select语句,根据其他列计算列

时间:2016-04-12 18:56:45

标签: mysql sql sql-function

我试图总结个人价格并使用逻辑来获得折扣。

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'

编写查询的正确方法是什么?

1 个答案:

答案 0 :(得分: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