所以我有一张产品表
Product ID | Product Name
===========+===============
1 | Tissues
2 | Glass
我有一张销售表
Sale ID | Product ID | Quantity | Price
===========+============+==========+=============
1 | 1 | 1 | 55
2 | 2 | 1 | 60
我有一张购买表
Batch ID | Total Value | Quantity | Product ID
=========+=============+==========+==================
1 | 100 | 100 | 1
2 | 10 | 50 | 2
3 | 1 | 1 | 2
所以我尝试使用查询根据平均成本计算利润
SELECT tblsale.product_id,
tblproduct.product_name,
SUM(tblsale.`quantity`) qty,
SUM(tblsale.`Price`*tblsale.`quantity`) sales,
(SELECT sum(total_value) / sum(quantity) VWAP
FROM tblpurchases
WHERE product_id = tblsale.product_id) average_price,
(average_price * qty) cost,
(sales-cost) profit
FROM tblsale, tblproduct
WHERE tblproduct.product_id = tblsale.`product_id`
GROUP by tblsale.`product_id`
但我似乎无法让它工作,我得到的“平均价格”是一个未知列,我该如何正确构建查询
最佳答案
SQL 不支持在同一 SELECT 子句中引用列别名 - 这就是您的 average_price
列返回 1054 错误的原因。您要么必须在子选择、派生表/内联 View 中执行您需要的任何操作,要么在必要时重用底层逻辑。这是逻辑重用的示例:
SELECT prod.product_id,
prod.product_name,
SUM(s.quantity) qty,
SUM(s.Price * s.quantity) sales,
SUM(pur.total_value) / SUM(pur.quantity) average_price,
SUM(pur.total_value) / SUM(pur.quantity) * SUM(s.quantity) cost,
SUM(s.Price * s.quantity) - (SUM(pur.total_value) / SUM(pur.quantity) * SUM(s.quantity)) profit
FROM tblproduct prod
LEFT JOIN tblsale s ON prod.product_id = s.product_id
LEFT JOIN tblpurchases pur ON pur.product_id = prod.product_id
GROUP BY s.product_id
我的查询使用的是 ANSI-92 JOIN 语法,我建议您的查询使用 ANSI-89 语法。参见 this question for more details .
关于mysql - 关联子查询mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9250186/