gpt4 book ai didi

php - Mysql Left Join 按月份为空月份的销售额表

转载 作者:太空宇宙 更新时间:2023-11-03 12:05:37 25 4
gpt4 key购买 nike

我需要制作一份包含当月总销售额的报告,其中没有销售额的月份的值为零。到目前为止,这是我正在处理的查询,我觉得我已经尝试了所有组合,但没有成功。为了我的报告目的,我需要 1 个数组中的月份和另一个数组中每个月的销售额。

查询:

$productSql = "SELECT months.monthnum, SUM(orders.total) FROM months LEFT JOIN orders ON months.monthnum = MONTH(orders.closeddate) WHERE orders.status = 'Closed' GROUP BY MONTH(orders.closeddate) ORDER BY months.monthnum ASC";
$productResult = mysql_query($productSql, $link);

while($productRow = mysql_fetch_array($productResult)){

$label[] = $productRow['months.monthnum'];
$data[] = $productRow['SUM(orders.total)'];
};

echo "[".json_encode($label).",".json_encode($data)."]";

结果:

[[null,null],["6000.00","3100.00"]]

如何让它在第一个数组中显示所有月份,而在第二个数组中显示没有销售的月份为零?我认为是 GROUP BY 害了我,但我需要它来增加销售额。帮助!

PS 我知道我应该停止使用 mysql,我会在这个项目完成后立即停止使用。谢谢!

编辑

var_dump 结果:

array(1) { [0]=> NULL } array(1) { [0]=> string(7) "6000.00" } array(2) { [0]=> NULL [1]=> NULL } array(2) { [0]=> string(7) "6000.00" [1]=> string(7) "3100.00" }

编辑 2

所以问题出在 WHERE 子句中。我需要 where 子句,因为我只想要已关闭的订单。当我取出 WHERE 子句时,它显示所有月份都为零,表示没有销售的月份,并正确地汇总有销售的月份。然而,它包括所有订单,而不仅仅是关闭的订单。我应该把 WHERE 子句放在哪里,这样我仍然可以获得所有月份?

最佳答案

您可以使用以下查询获取零值:

SELECT m.monthnum, coalesce(SUM(o.total), 0)
FROM months m LEFT JOIN
orders o
ON m.monthnum = MONTH(o.closeddate) AND o.status = 'Closed'
GROUP BY m.monthnum
ORDER BY m.monthnum ASC";

三个显着变化:

  • 将与 o.status 的比较移至 on 子句。
  • 聚合使用months 表而不是orders 表。
  • 总数使用 coalesce() 得到 0 而不是 NULL

我还引入了表别名,这使得查询更易于编写和阅读。

关于php - Mysql Left Join 按月份为空月份的销售额表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26781260/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com