【问题标题】:SQL select statement, calculating columns based on other columnsSQL select语句,根据其他列计算列
【发布时间】:2016-04-12 18:56:44
【问题描述】:

我正在尝试总结各个价格并使用折扣逻辑。

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'

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

【问题讨论】:

  • 您不能在select 子句中重复使用别名。
  • 所以我需要将整个逻辑子句复制粘贴到选择的每个部分吗?我需要做一个中间视图来保持价格,然后再做税收和总计吗?
  • 您可以复制/粘贴 select 子句中的逻辑

标签: mysql sql sql-function


【解决方案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

【讨论】:

    猜你喜欢
    • 2023-03-16
    • 2018-07-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-26
    • 2019-04-17
    • 1970-01-01
    • 2014-11-04
    • 2022-07-08
    相关资源
    最近更新 更多