查询我们没有销售任何东西的缺失月份? [英] Query missing months in which we haven't sold anything?
问题描述
我的查询是:
$sql="SELECT COUNT(`Variant`) AS tsold, MONTHNAME(`sold_date`) AS mname FROM `vehicle_sold` GROUP BY MONTH(`sold_date`) ";
$result = mysqli_query($conn,$sql);
while($row = mysqli_fetch_array($result)) {
echo $row["mname"],"---", $row["tsold"],"<br />";
}
这给了我以下结果:
January---1
February---2
March---7
April---11
May---6
July---1
六月没有销售,所以我想要的是例如返回六月---0"的查询.如果它还显示接下来的几个月直到 12 月,那就没问题了.我想要以下输出:
There are no sales in June so what I want is the query to return "June---0" for example. If it also shows the next months up to December it's ok. I'd like the following output:
January---1
February---2
March---7
April---11
May---6
June---0
July---1
Aug---0
Sept---0
Oct---0
Nov---0
Dec---0
推荐答案
如果你没有卖任何东西,我假设你在数据库中实际上没有数据.因此,在没有信息的情况下生成一个月有点困难.
I assume you have actually no data in the database if you did not sell anything. Hence its a bit hard to generate a month without info.
您需要一个包含所有月份的数组,与销售额对应.我建议你做这样的事情:
You want an array with all the months, corresponding with the amount of sales. I would suggest you make something like this:
准备一个包含月份的数组,所有值都为 0 作为默认值(您可以将此数组列表设置为更好",但现在仅作为示例).
Prepare an array with the months with all the values on 0 as default (you can make this array list 'nicer', but just now as example).
$data['March'] = 0;
$data['April'] = 0;
现在你可以像以前一样迭代
Now you can iterate like you did
while($row = mysqli_fetch_array($result)) {
$data[$row["mname"]] = $row["tsold"];
}
如果它没有被数据库填充,该值仍然是 0.否则它会被数据库值覆盖.
If it does not get filled by the database, the value would still be 0. Otherwise it gets overwritten by the database value.
这篇关于查询我们没有销售任何东西的缺失月份?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!