求和查询在连接到另一个表时更改值

时间:2012-02-21 16:57:35

标签: mysql totals

创建了以下查询,该查询生成总销售额报告。它产生了我预期的结果。我正在使用MySQL,查询如下:

SELECT detailed_report.title AS title,
detailed_report.nid AS nid,
detailed_report.price AS 'price',
SUM(detailed_report.quantity) AS 'total_quantity',
SUM(detailed_report.total) AS 'total_revenue' 
FROM (SELECT uc_order_products.nid AS 'nid',
uc_orders.order_id AS 'order_id',
uc_order_products.title AS title,
uc_order_products.price AS price,
uc_order_products.qty AS 'quantity',
(uc_order_products.qty * uc_order_products.price) AS 'total'
FROM uc_orders uc_orders
LEFT JOIN uc_order_products uc_order_products ON uc_orders.order_id = uc_order_products.order_id
WHERE uc_orders.order_status IN ('completed')) AS detailed_report
GROUP BY nid

产生的输出是:

enter image description here

当我向查询添加日期字段时,数量金额不正确。我不明白为什么会这样。以下是修订后的查询:

SELECT  event_dates.field_dates_value AS start_date,
event_dates.field_dates_value2 AS end_date,
detailed_report.title AS title,
detailed_report.nid AS nid,
detailed_report.price AS 'price',
SUM(detailed_report.quantity) AS 'total_quantity',
SUM(detailed_report.total) AS 'total_revenue' 
FROM (SELECT uc_order_products.nid AS 'nid',
uc_orders.order_id AS 'order_id',
uc_order_products.title AS title,
uc_order_products.price AS price,
uc_order_products.qty AS 'quantity',
(uc_order_products.qty * uc_order_products.price) AS 'total'
FROM uc_orders uc_orders
LEFT JOIN uc_order_products uc_order_products ON uc_orders.order_id = uc_order_products.order_id
WHERE uc_orders.order_status IN ('completed')) AS detailed_report
LEFT JOIN content_field_dates event_dates ON detailed_report.nid =event_dates.nid
GROUP BY nid

结果如下:

result of query

请注意,数量列值不正确。为什么是这样?有人可以解释我做错了什么以及如何纠正它?我完全不知所措。

由于

1 个答案:

答案 0 :(得分:0)

我会将您正在使用的sql解析成片段,并确定您正在使用的表格表达式是否有任何不同。

然后,如果没有问题,我会从选择中删除总和,看看与新表的左连接是否有任何差异,而不是没有。