I want to count totals for all mondays, tuesdays, etc. for any given (user selected) date range, StartDate (sDate) through EndDate (eDate). My current query shows all days within range and I'd like it to SUM my table "count" from each day as it is but display total of each day of week as one occurrence. Using image sample, I want my result to be:
Monday - 164
Tuesday - 139
Wednesday - 261
etc.
SQL
SELECT areaname,created, SUM(count) as totals FROM reports WHERE created
between '".$sDate."' AND '".$eDate."' AND area = '".$tArea."' GROUP BY areaname,
created ORDER BY id ASC
html
foreach ($counts as $row) { ?>
<tr><td><?php echo date('l',strtotime($row['reports']['created'])); ?></td>
<?php echo $row[0]['totals']; ?>
}
You can use the DATE_FORMAT() function to get the day of the week from a given date, then you can group by that. The syntax is DATE_FORMAT(date, '%W'). So:
SELECT areaname,
DATE_FORMAT(created, '%W') AS weekday,
SUM(count) AS totals
FROM reports
WHERE created BETWEEN '".$sDate."' AND '".$eDate."'
AND area = '".$tArea."'
GROUP BY areaname, weekday
ORDER BY id
Note that I left in areaname in the GROUP BY, so this will return one result for every combination of areaname/weekday. If you want totals for all areanames, just remove areaname from the GROUP BY clause.
Related
I have a table with 4 fields as follows
I want an Sql query to calculate a total salary for each month, where the result will be as follows
Do you just want group by and sum()?
select sum(salary) salary, month
from mytable
group by month
I am trying to get a COUNT of the last 12 months of appointments grouped by month for output into a chart. The following works fine but I need it to return 0 if no results for each month.
$query = "SELECT COUNT(id) as total_month FROM appointments WHERE created >= DATE(NOW()) - INTERVAL 365 DAY GROUP BY Month(created)";
$query = $mysqli->real_escape_string($query);
if($result = $mysqli->query($query)){
while($row = $result->fetch_array())
{
$month_total_appointments .= $row['total_month'].',';
}
}
echo $month_total_appointments;
================================================================
Simple table structure and example for appointments Table
id customer_name created
1 John 2020-05-01 08:00:00 <= stored as datetime
2 Mike 2020-04-01 09:00:00
3 Steve 2020-02-01 10:00:00
Output would be 0,0,0,0,0,0,0,0,1,0,1,1
======================================================
Current output is: 1,1,1
I've read some use a month table and LEFT JOIN but everything i've tried doesn't seem to work. Can anyone help please?
You won't get zeroes for rows that aren't there. Grouping combines rows that match particular criteria, but it can't fabricate them out of nothing.
That's why it's typical to include the grouping criteria in the results:
SELECT COUNT(id), MONTH(created) AS created_month
FROM appointments
WHERE created >= DATE(NOW()) - INTERVAL 365 DAY
GROUP BY created_month
Then you can expand that in your application code to fill in the missing values. The alternative is you need a fully populated list of all possible dates to JOIN against.
Keep in mind the MONTH() thing will wrap around and group January 2020 with January 2021. You may want to split this up:
SELECT COUNT(id), YEAR(created) AS created_year, MONTH(created) AS created_month
FROM appointments
WHERE created >= DATE(NOW()) - INTERVAL 365 DAY
GROUP BY created_year, created_month
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
Say I've got a simple mysql table with columns id, title, date. Each day can have several rows, but not every day has a row. For example there might be 5 rows with June 15th as the date, but zero rows with June 14th as the date. How can I get all results from the past 7 days, excluding June 14th because it has no rows. So I'm not just subtracting 7 days from the current date. I want to get only the past 7 days which have any rows at all.
Then I want to return each day as a single result, like a group by date, but by the year/month/day part of the timestamp, so that what I get back is only 7 results, and each result is like an array of individual rows.
I hope that makes sense. Any ideas?
Edit:
I realized I can do it something like this:
WHERE Date BETWEEN DATE_SUB( NOW(), INTERVAL DATEDIFF( NOW(), (SELECT Date FROM test GROUP BY Date LIMIT 7,1 ) ) DAY ) and NOW()
But this gives an SQL syntax error. What I'm trying to do is a subquery and group by date to get one result for each day, and return one result starting at offset 7, then do a DATEDIFF on that to get the number of days that DATE_SUB should put in the INTERVAL x DAYS
You won't be able to get the same day results back as an array, but you can group it by date, with the titles comma separated:
SELECT GROUP_CONCAT(title) AS titles, date
FROM test
WHERE date > DATE_SUB(CURDATE(), INTERVAL 7 DAY)
GROUP BY date;
Then in PHP, do something like this:
foreach ($results as $row)
{
echo $row['date'];
foreach ($row['titles'] as $title)
{
echo $title;
}
}
Figured it out: It works!
WHERE Date BETWEEN DATE_SUB(NOW(), INTERVAL (DATEDIFF( NOW(), (SELECT Date FROM test GROUP BY Date ORDER BY Date DESC LIMIT 8,1 ) ) ) DAY) and NOW()
I was missing a parentheses, and I had to add ORDER BY and DESC to the subquery.
I have a table with two fields - a field for "date" entered as day/month/year and a field "rate"
date | rate
24/01/05 | 1.9754
26/01/05 | 1.3723
...
and so on
So, I like to find minimum and maximum values of "rate" for each month of year(s). My query selects only one row
SELECT DISTINCT DATE_FORMAT(date, '%d-%m-%y') as Date, MIN(rate) as r, MAX(rate) as mr FROM rates
This will get the rate values for each month and year
SELECT
YEAR(date) AS thisYear,
MONTH(date) AS thisMonth,
MIN(rate) AS minRate,
MAX(rate) AS maxRate
FROM rates
GROUP BY thisYear ASC, thisMonth ASC
If you need to have the individual date(s) on which the min or max occurs you'll need some additional grouping in there, however the above should suffice for your original question.
To get the minimum and maximum values of "rate" for each month of year, you can modify the query as follows:
SELECT DATE_FORMAT(date, '%m-%Y') as Month_Year, MIN(rate) as Min_Rate, MAX(rate) as Max_Rate
FROM rates
GROUP BY DATE_FORMAT(date, '%m-%Y');
The GROUP BY clause groups the rows in the rates table based on the month and year of the date field. The MIN and MAX functions then calculate the minimum and maximum values of the rate field for each group. The DATE_FORMAT function is used to format the date field into a string with the format %m-%Y, where %m is the month (01-12) and %Y is the year (e.g., 2005).
This query will return a result set with one row for each unique month and year in the rates table, along with the minimum and maximum values of the rate field for that month and year.