1

我正在尝试创建一个查询,该查询将计算字段用于同一查询中的另一个计算,但它给了我一个错误。

如何以替代方式完成此操作。

询问 :

SELECT MIN(q.order_created) AS first_ordered,           
       MAX(q.order_created) AS last_ordered,
       SUM(IF(DATE_ADD(q.order_created,INTERVAL 12 MONTH) >= NOW(),pq.product_qty,0))/12 AS monthly_rate,                     
       SUM(pq.product_qty) AS yearly_sales,
       SUM((pq.product_cost_price * pq.product_qty) - pq.product_total_price ) AS **net_sold**,
       SUM(pq.product_cost_price * pq.product_qty)  AS **total_ordered**,
       **100 - ((total_ordered - net_sold)/total_ordered )*100 AS discount**,
       q.billing_account_id AS custid
 FROM quotes q
 LEFT JOIN products_quotes pq
   ON q.id = pq.quote_id
WHERE pq.product_id = '28e96e3d-460f-49fc-7d52-4f390b86d6b8'
  AND q.deleted = 0
  AND pq.deleted = 0
GROUP BY q.billing_account_id
ORDER BY q.order_created
GROUP BY q.billing_account_id
ORDER BY q.order_created

给出错误:“字段列表”中的未知列“total_ordered”。

4

1 回答 1

2

一开始不能这样使用 SUM 之类的聚合函数,因为它们的最终结果会在完成查询的结果集时计算,所以即使没有语法错误,计算的结果也是无效的。
第二个问题是你不能在同一个查询的同一个选择子句中使用别名,所以你可能想使用像这样的其他方式:

SELECT MIN(q.order_created) AS first_ordered,           
       MAX(q.order_created) AS last_ordered,
       SUM(IF(DATE_ADD(q.order_created,INTERVAL 12 MONTH) >= NOW(),pq.product_qty,0))/12 AS monthly_rate,                     
       SUM(pq.product_qty) AS yearly_sales,
       SUM((pq.product_cost_price * pq.product_qty) - pq.product_total_price ) AS net_sold,
       SUM(pq.product_cost_price * pq.product_qty)  AS total_ordered,
       100 - ((SUM(pq.product_cost_price * pq.product_qty) - SUM((pq.product_cost_price * pq.product_qty) - pq.product_total_price ))/SUM(pq.product_cost_price * pq.product_qty) )*100 AS discount,
       q.billing_account_id AS custid
FROM quotes q
LEFT JOIN products_quotes pq
    ON q.id = pq.quote_id
WHERE pq.product_id = '28e96e3d-460f-49fc-7d52-4f390b86d6b8'
    AND q.deleted = 0
        AND pq.deleted = 0
GROUP BY q.billing_account_id
ORDER BY q.order_created
GROUP BY q.billing_account_id
ORDER BY q.order_created

请注意,正如我所说,此查询的语法是有效的,但结果不是,正确的方法要长一点(比如使用子查询)。

于 2012-04-23T10:14:04.170 回答