2012-02-12 180 views
2

,所以我有产品表相关子查询的MySQL

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` 

但我似乎无法得到它的工作,我收到了“平均价”是一个未知的专栏中,我将如何构建查询正确

+0

什么是“总价值”和“数量”? – 2012-02-12 16:39:55

+0

总价值是所有商品在采购中的价值,数量是商品的单位数量(所以价值/数量)将是该特定批次的平均价格 – Akshat 2012-02-12 19:23:49

回答

2

SQL不支持在同一个SELECT子句中引用列别名 - 这就是为什么您的average_price列正在返回1054错误。您必须在子查询中进行所需的任何操作,派生表/内联视图,或者在必要时重新使用基础逻辑。这里是一个逻辑重用的例子:

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

+0

嗯,我想知道。这比内部选择运行速度快吗? – 2012-02-12 18:43:15

+0

@MostyMostacho:子选择性能取决于 - 对于大多数数据库,标量性能相同。但其他人需要检查,因为他们可以逐行执行(不好)。 – 2012-02-12 18:45:25

+0

这样想。感谢您的信息:) – 2012-02-12 18:46:55

-1

你是怎么到这个查询?它完全关闭。在编写查询时,从小处开始,然后构建它。你现在的查询是一个完整的混乱,并没有接近有效,有一个随机括号'通过它。

,使一个开始,使用缩进,使您的查询可读

SELECT p.product_id, p.product_name 
     , SUM(s.quantity) number_of_sales 
     , SUM(s.price) total_profit 
     , SUM(pu.quantity) purchase_quantity 
     , SUM(pu.value) purchase_value 
     , (SUM(pu.quantity) - SUM(s.quantity)) number_in_stock 
     , (SUM(s.price) - SUM(pu.value)) profit 
     , (SUM(pu.value)/SUM(pu.quantity)) avarage_purchase_price 
     FROM product p 
LEFT JOIN sales s ON s.product_id = p.product_id 
LEFT JOIN purchase pu ON pu.product_id = p.product_id   
    GROUP BY s.product_id, pu.product_id 

但我似乎无法得到它的工作,我收到了‘平均价’是未知列,怎么会我正确地构建查询

'平均价格'是什么?您希望如何计算平均价格? '平均成本'相同

+0

平均成本和平均价格将是相同的,平均值花费所有购买记录的加权平均成本 – Akshat 2012-02-12 19:24:24