在 SQL 查询中添加新列

Add new column in SQL query

我想使用查询结果创建新列,以便找到运费对收入的变化

原来的问题是运费增加10%对收入有什么影响。我目前正在使用 Northwind 数据集

select sum(UnitPrice*Quantity*(1-Discount))  - sum(Freight*1.1) as New,  sum(UnitPrice*Quantity*(1-Discount))  - sum(Freight) as Old, New-Old
from "Order Details", Orders;

SQL 查询不起作用,因为它无法识别新变量“New”和“Old”

我已经更新了建议的版本,但它生成了错误消息

NexusDB: Query534984250: Query execution failed: 
NexusDB: Correlation name for subquery expected:
SELECT New,Old,New-Old
FROM  (select
        sum(UnitPrice*Quantity*(1-Discount))  - sum(Freight*1.1) as New,
        sum(UnitPrice*Quantity*(1-Discount))  - sum(Freight) as Old
            FROM "Order Details"
               INNER JOIN  "Orders"  ON ("Order Details".OrderID = Orders.OrderID)
      )  ;

您可以在子查询运行中使用新列和旧列

但是您的(子)查询不会给您正确的结果,因为

From `Order Details`, `Orders`

是两个表之间的交叉联接,return 行太多,无法为您提供预期的结果

所以你会

FROM `Order Details` od 
    INNER JOIN  `Orders` o ON o.id = od.order_REf_id

然后您还必须检查结果是否是您要查找的结果

SELECT New,Old, New-Old
FROM  (select 
        sum(UnitPrice*Quantity*(1-Discount))  - sum(Freight*1.1) as New,
        sum(UnitPrice*Quantity*(1-Discount))  - sum(Freight) as Old
        from `Order Details`, `Orders`
      ) t1

最终效果会像

SELECT New,Old, New-Old
FROM  (select 
        sum(UnitPrice*Quantity*(1-Discount))  - sum(Freight*1.1) as New,
        sum(UnitPrice*Quantity*(1-Discount))  - sum(Freight) as Old
            FROM `Order Details` od 
               INNER JOIN  `Orders` o ON o.id = od.order_REf_id`
      ) t1