Mysql左加入和总和没有按月和年正确地工作

时间:2018-05-24 18:35:01

标签: mysql join sum left-join multiple-columns

我想在mysql上获得total_amount和received_amt与group by和月份和年份的总和。 但我遇到了一个问题。 问题是第二个表列总和与月份和年份不一致。

当前查询

SELECT t1.order_date,sum(IFNULL(t1.received_amt, 0)) as SumOfNO,
sum(IFNULL(t2.total_amount, 0)) as SumOfSM,
SUM(IFNULL(t1.received_amt, 0)  + IFNULL(t2.total_amount, 0)) AS Total
FROM `new_order` t1
LEFT JOIN
 (  select t2.sell_date,t2.total_amount, sum(total_amount) as Amount
    from sell_master t2
    group by YEAR(t2.sell_date), MONTH(t2.sell_date) 
 ) t2
 ON format(t1.order_date,'yyyy-MM') = format(t2.sell_date,'yyyy-MM')
GROUP BY YEAR(t1.order_date), MONTH(t1.order_date)
ORDER BY t1.order_date DESC

示例:

第一张表:new_order

第二张表:sell_master

表格结构:

NEW_ORDER

+----------------------------------------+
|order_date(date) | received_amt(double) |
+----------------------------------------+
|2007-10-06       | 245                  |
|2007-10-06       | 310                  |                             
|2007-10-06       | 275                  |                             
|2007-10-06       | 300                  |
+----------------------------------------+

sell_master

+----------------------------------------+
|sell_date(date)  | total_amount(double) |
+----------------------------------------+
|2007-10-06       | 10                   |
+----------------------------------------+

当前结果

+---------------------------------------+
|order_date | SumOfNO | SumOfSM | Total |
+---------------------------------------+
|2007-10-06 | 1130    | 40      |1170   |
+---------------------------------------+

预期结果

+---------------------------------------+
|order_date | SumOfNO | SumOfSM | Total |
+---------------------------------------+
|2007-10-06 | 1130    | 10      |1140   |
+---------------------------------------+

2 个答案:

答案 0 :(得分:1)

您不应在主查询中使用SUM(t2.total_amount)。您已经计算了子查询中的总和,您应该使用它。发生的事情是,您将t2.total_amount乘以匹配的new_order中的行数。

还没有必要在IFNULL()内使用SUM(),因为SUM()会忽略空值(大多数聚合函数都会这样做)。

子查询应选择日期的年份和月份,以便您可以加入这些目录,而不是使用date_format

由于您按月分组,因此您不应该选择t1.order_date - 这只会从该组中选择一个月中的随机日期。您应该以{{1​​}}格式显示月份。

YYYY-MM

DEMO

答案 1 :(得分:0)

您希望选择一个表的聚合结果(此处为总和)以及另一个表的聚合结果。因此,构建两个聚合,然后加入。

select 
  year_month, 
  o.total as sumofno,
  coalesce(s.total, 0) as sumofsm,
  o.total + coalesce(s.total, 0) as total
from
(
  select format(order_date, 'yyyy-MM') as year_month, sum(received_amt) as total
  from new_order
  group by format(order_date, 'yyyy-MM')
) o
left join
(
  select format(sell_date, 'yyyy-MM') as year_month, sum(total_amount) as total
  from sell_master
  group by format(sell_date, 'yyyy-MM')
) s using (year_month)
order by month desc;