Group MySQL data based on year - php

I have this query:
SELECT DATE_FORMAT(odd_date_created + INTERVAL -3 DAY, '%Y') AS `year`
, DATE_FORMAT(odd_date_created + INTERVAL -3 DAY, '%b') AS `month`
, COUNT(odd_Id) as total, status, odd_date_created FROM odd_data
WHERE status = 1
GROUP BY DATE_FORMAT(odd_date_created + INTERVAL -3 DAY, '%m')
HAVING DATE_FORMAT(odd_date_created + INTERVAL -3 DAY,'%Y') = 2018
$yearToDate will dynamically from select dropdown. When user select 2017, managed to get the data but if you select 2018 there is no data retrun.
Can somebody help me.

The problem is with your GROUP BY clause. Since you are grouping by month and the first data for each month is in 2017, the value of DATE_FORMAT(odd_date_created + INTERVAL -3 DAY,'%Y') in the select will almost certainly (although it's not guaranteed as there is no order implied) be 2017. You need to GROUP BY the year as well so that you get data for each month in each year. Then you can select specific years using HAVING. Note that you can use aliases in GROUP BY and HAVING clauses, so you can rewrite your query as:
SELECT DATE_FORMAT(odd_date_created + INTERVAL -3 DAY, '%Y') AS `year`,
DATE_FORMAT(odd_date_created + INTERVAL -3 DAY, '%b') AS `month`,
COUNT(odd_Id) as total, status, odd_date_created FROM odd_data
WHERE status = 1
GROUP BY year, month
HAVING year = 2018
Note that having status and odd_date_created in this query is pointless as they will return random values from the set of entries which match the WHERE and HAVING clauses.

Related

MYSQL Last month Query is not returning first 9 days

I am querying records from the last calendar month. As it is February, it should return all the records that were added on January this year.
My Query:
`SELECT * FROM table_name WHERE date >=
DATE_ADD(LAST_DAY(DATE_SUB(NOW(), INTERVAL 2 MONTH)), INTERVAL 1
DAY) AND date <= DATE_ADD(LAST_DAY(DATE_SUB(NOW(), INTERVAL 1
MONTH)), INTERVAL 0 DAY) AND campaign = '$campaign' ORDER BY date
ASC`
It returns some records but skips the first 9 days. It starts showing records from 10th of the previous month. What am I missing here?
check your date field type and make sure you have not mistaken it with varchar.
SELECT * FROM table_name WHERE
(MONTH(date) = (MONTH(NOW()) - 1) AND YEAR(date) = YEAR(NOW()))
OR
(MONTH(date) = 12 AND MONTH(NOW())=1 AND YEAR(date) = (YEAR(NOW()) - 1) AND campaign = '$campaign' ORDER BY date
ASC`
Try To Get Data in step by step like,
First, you should try below query.
SELECT Date, DATE_ADD(LAST_DAY(DATE_SUB(NOW(), INTERVAL 2 MONTH)), INTERVAL 1 DAY) AS StartDate, DATE_ADD(LAST_DAY(DATE_SUB(NOW(), INTERVAL 1 MONTH)), INTERVAL 0 DAY) AS EndDate FROM MyTable
Second, If First Step give right date then get your data by directly writing your date rather than DATE_ADD function in where clause.
Third, If These will Give you write DATA then try to fetch data using DATE_ADD function.
Replay If you will get solution.
SELECT * FROM table_name WHERE date between DATE_SUB(DATE_SUB(CURRENT_DATE,INTERVAL DAYOFMONTH(CURRENT_DATE)-1 DAY),INTERVAL 1 MONTH) AND DATE_SUB(DATE_SUB(CURRENT_DATE,INTERVAL DAYOFMONTH(CURRENT_DATE)-1 DAY),INTERVAL 1 DAY) AND campaign = '$campaign' ORDER BY date ASC

MySQL Query results based on month

I really need some help. Not MySQL friendly, muddled through this last few days but now stuck...
Need to take the below query and modify it to pull out only records closed in month of "January" for instance. Is this possible from the below? Cant figure it...
<?php
$recentlyClosedDays = 7;
?>
$query1 = "
SELECT HD_TICKET.ID as ID,
HD_TICKET.TITLE as Title,
HD_STATUS.NAME AS Status,
HD_PRIORITY.NAME AS Priority,
HD_TICKET.CREATED as Created,
HD_TICKET.MODIFIED as Modified,
S.FULL_NAME as Submitter,
O.FULL_NAME as Owner,
HD_TICKET.RESOLUTION as Resolution,
(SELECT COMMENT FROM HD_TICKET_CHANGE WHERE HD_TICKET_ID=HD_TICKET.ID ORDER BY TIMESTAMP DESC LIMIT 1) as Comment,
HD_TICKET.CUSTOM_FIELD_VALUE0 as Type
FROM HD_TICKET
JOIN HD_STATUS ON (HD_STATUS.ID = HD_TICKET.HD_STATUS_ID)
JOIN HD_PRIORITY ON (HD_PRIORITY.ID = HD_TICKET.HD_PRIORITY_ID)
LEFT JOIN USER S ON (S.ID = HD_TICKET.SUBMITTER_ID)
LEFT JOIN USER O ON (O.ID = HD_TICKET.OWNER_ID)
WHERE (HD_TICKET.HD_QUEUE_ID = $mainQueueID)
AND (HD_STATUS.STATE like '%Closed%')
AND (HD_TICKET.TIME_CLOSED >= DATE_SUB(NOW(), INTERVAL $recentlyClosedDays DAY))
ORDER BY HD_TICKET.TIME_CLOSED DESC
";
Any help would be greatly apprecaited and beer will be owed :)
To select DATE, DATETIME, or TIMESTAMP values in the current month, you do this.
WHERE timestampval >= DATE(DATE_FORMAT(NOW(), '%Y-%m-01'))
AND timestampval < DATE(DATE_FORMAT(NOW(), '%Y-%m-01')) + INTERVAL 1 MONTH
For the previous month you can do this:
WHERE timestampval >= DATE(DATE_FORMAT(NOW(), '%Y-%m-01')) - INTERVAL 1 MONTH
AND timestampval < DATE(DATE_FORMAT(NOW(), '%Y-%m-01'))
For the previous year you could do this:
WHERE timestampval >= DATE(DATE_FORMAT(NOW(), '%Y-01-01')) - INTERVAL 1 YEAR
AND timestampval < DATE(DATE_FORMAT(NOW(), '%Y-01-01'))
You can summarize (aggregate) tables by month like this:
SELECT DATE(DATE_FORMAT(timestampval , '%Y-%m-01')) AS month_starting,
SUM(whatever) AS total,
COUNT(whatever) AS transactions
FROM table
GROUP BY DATE(DATE_FORMAT(timestampval , '%Y-%m-01'))
This all works because this expression:
DATE(DATE_FORMAT(sometime, '%Y-%m-01'))
takes an arbitrary sometime value and returns the first day of the month in which the timestamp occurs. Similarly,
DATE(DATE_FORMAT(sometime, '%Y-01-01'))
returns the first day of the year. You can then use date arithmetic like + INTERVAL 1 MONTH to manipulate those first days of months or years.
Here's a more complete writeup on this topic. http://www.plumislandmedia.net/mysql/sql-reporting-time-intervals/

Getting sum of duplicated date entries from last month, week, day

I have a table with 3 columns: id, updated_at, click_sum.
Many rows have the exact same updated_at value which makes it hard to simply retrieve the data, order by updated_at and display the sums in a chart.
Since there are multiple sums for the same dates which screws the chart.
What I try to achieve is to get the following output:
update_at | click_sum
-----------+-----------
date1 | 100
date2 | 3
date3 | 235
date4 | 231
Optionally only those dates which are form the last month, week or day AND not simply the dates which are NOW() - 1 month.
The current query I build is very large and doesn't work that well.
It groups by dates (no duplicated dates appear) and SUM()s the clicks correctly but defining from when (last month, week, day) the dates are doesn't seem to work properly.
Query: ($interval stands for MONTH or DAY or SECOND or WEEK)
SELECT d.updated_at, SUM(d.clicks_sum) AS click_sum
FROM aggregated_clicks d
JOIN
(
SELECT c.id, MAX(StartOfChains.updated_at) AS ChainStartTime
FROM aggregated_clicks c
JOIN
(
SELECT DISTINCT a.updated_at
FROM aggregated_clicks a
LEFT JOIN aggregated_clicks b ON (b.updated_at >= a.updated_at - INTERVAL 1 DAY AND b.updated_at < a.updated_at)
WHERE b.updated_at IS NULL
) StartOfChains ON c.updated_at >= StartOfChains.updated_at
GROUP BY c.id
) GroupingQuery
ON d.id = GroupingQuery.id
WHERE GroupingQuery.ChainStartTime >= DATE_SUB(NOW(), INTERVAL 1 $interval)
GROUP BY GroupingQuery.ChainStartTime
ORDER BY GroupingQuery.ChainStartTime ASC
maybe I'm assuming too much about the nature of your question (and the table it refers to), but I think this can be done much more simply than the query you've shown.
figuring the latest completed month isn't very hard.
it starts with knowing the first date of this current month -- use this:
date_sub(curdate(), interval (extract(day from curdate())-1) day)
and to know the first day of that previous month, use this:
date_sub(date_sub(curdate(), interval extract(day from (curdate())-1) day), interval 1 month)
so if you want to get the sums for just the days in between -- i.e. the latest completed month, use this:
select updated_at, sum(click_sum) from aggregated_clicks
where updated_at >= date_sub(date_sub(curdate(), interval extract(day from (curdate())-1) day), interval 1 month)
and updated_at < date_sub(curdate(), interval (extract(day from curdate())-1) day)
group by updated_at;
figuring the lastest completed week is just as easy. this example will assume a Sunday-Saturday week.
because of the way the ODBC standard defines date numbers, it's easy to find the end (Saturday) of the previous week:
date_sub(curdate(), interval dayofweek(curdate()) day)
and the beginning (Sunday) of that week is six days before that:
date_sub(curdate(), interval (dayofweek(curdate())+6) day)
so if you want to get the sums for just the days in between -- i.e. the latest completed week, use this:
select updated_at, sum(click_sum) from aggregated_clicks
where updated_at >= date_sub(curdate(), interval (dayofweek(curdate())+6) day)
and updated_at <= date_sub(curdate(), interval dayofweek(curdate()) day)
group by updated_at;
and of course figuring based on the latest completed day is super easy.
to get the date of the previous day, use this:
date_sub(curdate(), interval 1 day)
so if you want the sums just for yesterday, use this:
select updated_at, sum(click_sum) from aggregated_clicks
where updated_at = date_sub(curdate(), interval 1 day)
group by updated_at;
NOTE: I've tested these queries using MySQL 5.1, YMMV.
----------
UPDATE: since the date column is a datetime, simply change all references to updated_at in my queries to date(updated_at) like so:
month case:
select date(updated_at), sum(click_sum) from aggregated_clicks
where date(updated_at) >= date_sub(date_sub(curdate(), interval extract(day from (curdate())-1) day), interval 1 month)
and date(updated_at) < date_sub(curdate(), interval (extract(day from curdate())-1) day)
group by date(updated_at);
week case:
select date(updated_at), sum(click_sum) from aggregated_clicks
where date(updated_at) >= date_sub(curdate(), interval (dayofweek(curdate())+6) day)
and date(updated_at) <= date_sub(curdate(), interval dayofweek(curdate()) day)
group by date(updated_at);
yesterday case:
select date(updated_at), sum(click_sum) from aggregated_clicks
where date(updated_at) = date_sub(curdate(), interval 1 day)
group by date(updated_at);

mysql select only next week data

I have a date field in my database i.e film_release_date.
So what is mysql query to fetch the next week data from table.
I run this query but its not working properlly.
SELECT
*,
DATE_FORMAT(film_release_date,'%e-%b-%Y') AS release_date
FROM gf_film
WHERE
MONTH(film_release_date)=MONTH(CURRENT_DATE)
AND YEAR(film_release_date)=YEAR(CURRENT_DATE)
AND film_release_date>=(CURRENT_DATE)
ORDER BY film_release_date DESC
Actually its for movie website i have several movies in my database so i need a query which fetch every next week movie that means movies that will release in next week means next friday.If i run this today i.e 13 then it shows all movies between 15 to 22 and if run this between 15 to 22 then it shows data from 22 to 29
set #d := date_add(CURRENT_DATE, interval 7 day);
set #week_start := #d - interval (dayofweek(#d) + 1) day;
set #week_end := #d + interval (6 - dayofweek(#d)) day;
SELECT *,
DATE_FORMAT(film_release_date,'%e-%b-%Y') AS release_date
FROM gf_film
WHERE film_release_date between #week_start and #week_end
ORDER BY film_release_date DESC
to get next week data you can simple apply below logic :
SELECT something FROM tbl_name
-> WHERE DATE_SUB(CURDATE(),INTERVAL 7 DAYS)
REFERENCE
Little late, but none of the answers works properly. You can use yearweek function to get week number of the year. So you get the week number of now (this week) or now() + interval 7 day to get next week. Examples:
THIS WEEK
SELECT *, DATE_FORMAT(film_release_date,'%e-%b-%Y') AS release_date
FROM gf_film
WHERE YEARWEEK(film_release_date) = YEARWEEK(NOW())
ORDER BY film_release_date DESC
NEXT WEEK
SELECT *, DATE_FORMAT(film_release_date,'%e-%b-%Y') AS release_date
FROM gf_film
WHERE YEARWEEK(film_release_date) = YEARWEEK(NOW() + INTERVAL 7 DAY)
ORDER BY film_release_date DESC

HOw to SELECT * (all) which date start from the last day of last month to the first day of next month

use PHP and MySQL and want to use SELECT statement which date_post(datetime variable) start at the last date of last month and to date the first day of next month, help me please.
Thank you in advance.
my database: 'id', 'content', 'image', 'date_post',
etc. and I try to use
$today = getdate();
$thisyear=$today['year'];
$thismon=$today['mon'];
$date_start=$thisyear.'-'.$thismon.'-01';
$date_end=$thisyear.'-'.($thismon+1).'-01';
$sql="SELECT *, DATE_FORMAT(date_post, '%d-%m-%Y') AS datepost
FROM my_table
WHERE date_post BETWEEN date('$date_start')
AND date('$date_end')
ORDER BY date_post DESC";
It makes with one query in MySQL, without any PHP:
SELECT * FROM `table_name`
WHERE DATE(`date_post`) >= DATE_FORMAT(CURDATE() - INTERVAL 1 MONTH, CONCAT('%Y-%m-', DAY(LAST_DAY(CURDATE() - INTERVAL 1 MONTH))))
AND DATE(`date_post`) <= DATE_FORMAT(CURDATE() + INTERVAL 1 MONTH, '%Y-%m-01');
Ensuring that the query will not scan the full table but will use the index of date_post (if there is one!):
SELECT *
FROM myTable
WHERE date_post < LAST_DAY(CURDATE())
+ INTERVAL 2 DAY
AND date_Post >= LAST_DAY( LAST_DAY( CURDATE()) - INTERVAL 1 MONTH )
If it is run today ( 2011-07-01 ), it will give all datetimes between 2011-06-31 00:00:00 and 2011-08-01 23:59:59.

Categories