0

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

[Jenuary] => 200

How do I get one array in both months?

I want result:

[January] => 200,
[February] => 221

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

first answer already fix my problem, thank you too..
1

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.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.