I have a database table having date and amount column, I have to make the some of them monthly, so how can I do it.
Please refer image for database table:
Actually I wanted the output as in this month this much is the total, e.g if we have 5 entries in the month of Jan then I wanted the sum of all the 5 entries in the month of Jan, how can I do it?
select sum(total_amt)
from table_name
group by month(paydate)
SELECT SUM(total_amt) as TotalAmount
FROM table_name
WHERE DATE(paydate) >= '2016-01-01'
ND DATE(paydate) <= '2016-01-31'
This would give you back one row containing the total amount of january 2016.
2nd method:
SELECT SUM(total_amt) as TotalAmount
FROM table_name group by month(paydate)
This would give you back a row for each month with the total amount.
select all rows where date start in march...
$result = mysqli_query($con,"SELECT * FROM table WHERE paydate LIKE '2016-03%");'
then echo the count it in your page...
echo "March entries: " . mysqli_num_rows($result);
make sure your 'paydate' field uses date
data type,then you can use
SELECT SUM(total_amt) AS Sum FROM `Table_Name` GROUP BY MONTH(paydate);
My recommendations is use the function date() of php to obtain month of the date from the timestamp with:
$month = date_parse($date_parse)['month']; // 1-12
Example: Assuming that $query
has the database result with the rows containing the total amount and the payday, you could make:
$months_payments = array();
$current_month = '';
$payments_arr = array();
foreach ($query as $row){
$pay_month = date_parse($row['payday'])['month'];
if(strcmp($current_month, $pay_month)) != 0){
$months_payments[$current_month]=$payments_arr;
$current_month = $pay_month;
$payments_arr = array();
}
$payments_arr.push($row['total_amt'])
}
// To add the last month
$months_payments[$current_month]=$payments_arr;
$current_month = $pay_month;
After this sorting you should just need to sum the elements in each month array. If you want to also differentiate for year, you will need to adapt the code.