所以我的问题是
SELECT
c.customer_id,
c.customer_lastname,
c.customer_firstname,
SUM(IF(op.product_id > 0, IF(op.product_quantity > 0, op.product_quantity, 0), 0)) AS sold_products_count,
SUM(IF(op.product_id > 0, IF(op.product_quantity < 0, -1 * op.product_quantity, 0), 0)) AS returned_products_count,
ROUND(100 * SUM(IF(op.product_id > 0, IF(op.product_quantity < 0, -1 * op.product_quantity, 0), 0))
/ SUM(IF(op.product_id > 0, IF(op.product_quantity > 0, op.product_quantity, 0), 0))) as returned_products_percent,
ci.customer_street_address,
ci.customer_phone
FROM
`order_products` AS op
LEFT JOIN (
SELECT order_id, MIN(o.order_datetime) as first_order_date,
MAX(o.order_datetime) as last_order_date,
DATEDIFF(NOW(), MAX(o.order_datetime)) as days_since_last_order,
COUNT(DISTINCT o.order_id) as orders_count,
SUM(o.order_total) as orders_total
FROM `order` as o
GROUP BY order_id) as o2 ON o2.order_id = op.order_id
LEFT JOIN customer AS c ON o.customer_id = c.customer_id
LEFT JOIN customer_address AS ci USING (customer_id)
GROUP BY
customer_id
ORDER BY
customer_id ASC limit 100
我得到一个错误- #1054 -未知列'o.customer_id'在'on clause'中,我不知道如何解决。我的左连接-选择组合是否正确完成?
1条答案
按热度按时间svmlkihl1#
您需要在计算总计的子查询中联接
order
和order_products
。并且这需要按客户ID分组。然后,您将其与主查询中的客户表联接。任何聚合函数都不能在主查询中,因为这样它们将乘以您要联接的地址数。您需要一个单独的子查询,该子查询只从
order
聚合,而不从order_products
聚合,这样这些聚合就不会乘以乘积。您不需要在主查询中进行任何分组,因为主查询中现在没有聚合函数。您将获得每个客户地址的单独结果行--订单信息相同,但地址不同。