我正在尝试创建一个查询,该查询在同一查询中使用计算字段进行另一次计算但是它给了我一个错误。
如何以其他方式完成此操作。
查询:
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'。
答案 0 :(得分:1)
首先,您不能以这种方式使用SUM等聚合函数,因为它们的最终结果将在完成查询的结果集时计算,因此即使它没有语法错误,计算结果也无效。登记/> 第二个问题是你不能在同一个查询的同一个select子句中使用别名,所以你可能想要使用这样的其他方式:
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
注意,正如我所说,此查询的语法有效,但结果不是&正确的方法有点长(比如使用子查询)。