[英]MySQL multiple count by one query
I try to count how many were sold by the month and get one Array.我尝试计算每月售出的数量并获得一个阵列。
$q = SELECT COUNT(id) AS January FROM tableName WHERE status='sold' AND month = '1'
UNION
SELECT COUNT(id) AS February FROM tableName WHERE status='sold' AND month = '2'
$row = mysqli_fetch_array(mysqli_query($connection, $q));
print_r($row);
UNION don't work, when I'm trying print_r(array), I get result UNION 不起作用,当我尝试使用 print_r(array) 时,我得到了结果
[Jenuary] => 200
How do I get one array in both months?如何在两个月内获得一个阵列?
I want result:我想要结果:
[January] => 200,
[February] => 221
You can try this query to get exact result you want.您可以尝试此查询以获得所需的确切结果。
select MONTHNAME(STR_TO_DATE(month, '%m')) as month, count(*) cnt
from tablename
where status = 'sold'
group by month
Only for specific month仅限特定月份
select MONTHNAME(STR_TO_DATE(month, '%m')) as month, count(*) cnt
from tablename
where status = 'sold' and month in(1, 2)
group by month
I think you want conditional aggregation:我认为你想要条件聚合:
select sum(month = 1) as january, sum(month = 2) as february
from tablename
where status = 'sold' and month in (1, 2)
This generates just one row, with two columns called january
and february
, each containing the number of rows for that month.这仅生成一行,其中两列称为january
和february
,每列包含该月的行数。
Or maybe you want one row per month.或者,也许您希望每个月排一排。 In that case you can use simple aggregation:在这种情况下,您可以使用简单的聚合:
select month, count(*) cnt
from tablename
where status = 'sold' and month in (1, 2)
group by month
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.