MySQL multiple count by one query - php

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

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.
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

Related

Select totals from database table based on month

I have a table which has product quantity column and the database has multiple entries in a single month.
Date format is (YYYY-MM-DD)
Date Quantity
2016-03-01 1200
2016-03-05 200
2016-04-05 500
2016-04-10 1000
2016-05-05 850
2016-05-10 50
So I want data as:
March (2016-03-01 to 2016-03-31) = 1400
April (2016-04-01 to 2016-04-30) = 1500
May (2016-05-01 to 2016-05-31) = 900
How can I do this?
Use the following query and it will return the result that you want.
' date field ' is the name of the column where date is inserted and Tablename is the name of the Table.
SELECT MONTH(date field) as month , YEAR(date field) as year , SUM(quantity) as
quantity FROM Tablename GROUP BY MONTH( date field )
select MONTH(Date) As dt , SUM(quantity) total from #Table1
GROUP BY MONTH(Date)
You can use DATE_FORMAT to convert the date field into just the year-month format, select the SUM of the quantity field, and then GROUP_BY the year-month field.
SELECT DATE_FORMAT('%Y-%m', `date`) as `ym`, SUM(`quantity`) FROM `table` GROUP BY `ym` ORDER BY `ym` ASC
You can try grouping by the month and year, taking the sum of the quantity field as an aggregate.
SELECT MONTH(Date), YEAR(Date), SUM(quantity)
FROM yourTable
GROUP BY MONTH(Date), YEAR(Date)
If you want the fancy output with actual date ranges, that would be a bit more work to do. Those dates may not exist in your original data set, so it could require a date table. And handling February in a leap year could be a real pain.
Use the following query same as it is it will return what you want
SELECT CONCAT(DATE_FORMAT(date,'%b'),' ',
(SELECT CONCAT('(',YEAR(date),'-',LPAD(MONTH(date),2,0),'-01 - ')
), (SELECT concat(last_day(date),')')
)) dates, SUM(quantity) qty FROM DATES GROUP BY MONTH(date) ORDER BY MONTH(date)

select month date from database

I have this code to select distinct value and give me the number of values.
I want to select only the value in this month.
Example : give me all value of month 06 only in the same way distinct value number only in the month 06 or 05
Remarque: the date type in the database is varchar not date.
$sql=mysqli_query($conn,"select db_shopname, COUNT(db_shopname) as num FROM
(select tbl_order.db_shopname from tbl_order union all select tbl_item.db_shopname from tbl_item)t
GROUP BY db_shopname ")or die(mysqli_error($conn));
while($res=mysqli_fetch_array($sql)){
echo $res['db_shopname'];echo" ";echo"(";echo $res['num'];echo")";echo"<br/>";
}
To pull the month out of the varchar field use:
MONTH(STR_TO_DATE(db_date ,'%Y/%m%d'))=MONTH(NOW())
Add this into where condition
EDIT:
I don't know its work for what you expecting but try it .
select db_shopname, COUNT(db_shopname) as num
FROM
(select tbl_order.db_shopname
from
tbl_order
where MONTH(STR_TO_DATE(`db_date` ,'%Y/%m%d'))=MONTH(NOW())
union
all
select tbl_item.db_shopname
from tbl_item
where MONTH(STR_TO_DATE(`db_date` ,'%Y/%m%d'))=MONTH(NOW()))t
GROUP BY db_shopname
hi if you want to convert date varchar to date for searching you can use below example
select date_format(str_to_date('31/12/2010', '%d/%m/%Y'), '%Y-%m-%d') - return 2010-12-31
If you want only year
select date_format(str_to_date('31/12/2010', '%d/%m/%Y'), '%Y') - return 2010
If you want only month
select date_format(str_to_date('31/12/2010', '%d/%m/%Y'), '%m') - return 12
If you want only day
select date_format(str_to_date('31/12/2010', '%d/%m/%Y'), '%d') - return 31
Example
select count(name) from test where MONTH(str_to_date(date, '%d/%m/%Y')) = 06 group by name

to show total record in wanted date row

I retrieved data from my table by summing result and show in table.I want to show sum result record between date='2014-01' and date='2014-04' in 2014-04 column name.And then,I want to retrieve other sum result in 2014-05 to current date.
How can I do that?
SELECT MONTH(regist_timestamp) AS Month, YEAR(regist_timestamp) AS Year,
count(id) AS numberOfVisits FROM ash_members WHERE
DATE(regist_timestamp) < CURDATE() GROUP BY
DATE_FORMAT(`regist_timestamp`,'%Y/%m' )
Format the date on SELECT then GROUP BY. Try with -
SELECT MONTH(regist_timestamp) AS Month, YEAR(regist_timestamp) AS Year,
count(id) AS numberOfVisits, DATE_FORMAT(`regist_timestamp`,'%Y/%m' ) formatted_date
FROM ash_members
WHERE DATE(regist_timestamp) < CURDATE()
GROUP BY formatted_date

PHP and SQL - How to select highest sum of all months in a current year?

So I have table 'item' in database with attributes: id, dateItem, price.
I want to find MAX(SUM(price)) for some month in a current year.
id dateItem (Format: yyyy-mm-dd) price
1 25.06.2015. 986,69
2 21.06.2015. 1564
3 22.03.2015. 23,56
4 21.03.2015. 187,23
5 01.03.2015. 489,33
6 06.10.2015. 975,26
I came up with something like this, but I know it's not ok. Please, help :s
$sql = "SELECT MAX(SUM(price)) FROM item WHERE DATE('Y') = 2015 AND
dateItem between DATE('Y/m/1') and DATE('Y/m/31')";
You can't nest aggregation functions. You need to use a subquery.
SELECT MAX(pricesum)
FROM (SELECT SUM(price) AS pricesum
FROM item
WHERE YEAR(dateItem) = YEAR(NOW())
GROUP BY MONTH(dateItem)) AS subquery
You can do this with ORDER BY and LIMIT:
SELECT SUM(price) AS pricesum
FROM item
WHERE YEAR(dateItem) = YEAR(NOW())
GROUP BY MONTH(dateItem)
ORDER BY pricesum DESC
LIMIT 1;
If you want to know the month as well, you can include that in the SELECT clause.

Mysql IFNULL working only once in a multiple SELECT query

I'm trying to build a month graphic using a MySQL query. I'm checking how many rows there are in a table for each month in a single query using the UNION command. Example with 3 months bellow:
$query =
"SELECT IFNULL((SELECT SUM(score) FROM statistics WHERE MONTH(date) = 1), 0) AS total UNION
SELECT IFNULL((SELECT SUM(score) FROM statistics WHERE MONTH(date) = 2), 0) AS total UNION
SELECT IFNULL((SELECT SUM(score) FROM statistics WHERE MONTH(date) = 3), 0) AS total";
$stats_query = mysqli_query ($db_connection, $query);
$result = "";
while ($row = mysqli_fetch_assoc($stats_query)) {
$result .= $row['total'].",";
}
echo ($result);
// OUTPUT: 0,176,68,
As you can see, I'm telling mysql to return me a "0" in case there are no rows for that month (which is the case for January).
There are a total of 12 SELECTS in that query (I copied just 3 to save space), one for each month. Some months will return a value, others won't (which the IFNULL should then convert to a "0").
My final output, for all the 12 months, should look like this:
// OUTPUT: 0,176,68,0,0,0,0,0,12,15,176,43,
BUT... if there is more than one SELECT that returns no rows, the query won't add another "0" to the result. My final result ends up being like this:
// OUTPUT: 0,176,68,12,15,176,43,
It's like the IFNULL is only executed once, even though he's present in all the 12 SELECTS...
Am I doing something wrong? Can anyone spot an error in my code or something?
Thank you!
Use UNION ALL instead of UNION to get all results:
SELECT IFNULL((SELECT SUM(score) FROM statistics WHERE MONTH(date) = 1), 0) AS total UNION ALL
SELECT IFNULL((SELECT SUM(score) FROM statistics WHERE MONTH(date) = 2), 0) AS total UNION ALL
SELECT IFNULL((SELECT SUM(score) FROM statistics WHERE MONTH(date) = 3), 0) AS total
UNION returns only DISTINCT rows.
From doc:
The default behavior for UNION is that duplicate rows are removed from
the result.

Categories