MySQL Date Transformation in Group By - mysql

I have the following query:
SELECT COUNT(*) AS COUNT, DATE(POST_DATE) AS POST_DATE
FROM POST
WHERE POST_DATE>='?'
GROUP BY DATE(POST_DATE)
POST_DATE is actually a DATETIME.
Now, this query works fine except I'd like to make one small adjustment. I would like all posts before 6am count as a post from yesterday.
So somehow I need to say: if POST_DATE.hour < 6 -> date(POST_DATE) - 1
But I'm not sure how to this in this query... or if that's even possible.
My first thought is to do another query with the date transformation and then wrap that result with the count and groupby
Any thoughts from an SQL wizard?

You want all posts from before 6am on day n+1 to be tabulated as if they were from day n. That means you want them to be tabulated as if they were made six hours earlier than the actual time stamp.
Here's what you do.
SELECT COUNT(*) AS COUNT,
DATE(POST_DATE - INTERVAL 6 HOUR) AS POST_DATE
FROM POST
WHERE DATE(POST_DATE - INTERVAL 6 HOUR) = ?
GROUP BY DATE(POST_DATE - INTERVAL 6 HOUR)
In all cases, you just offset the POST_DATE by six hours. I assume that when you choose a particular day for posts you want it to run from 06:00 to 06:00, not midnight to midnight.
Notice that your WHERE clause defeats the use of an index on POST_DATE, because of the function on the column value. You may want this instead.
WHERE POST_DATE >= ? + INTERVAL 6 HOUR
AND POST_DATE < ? + INTERVAL 1 DAY + INTERVAL 6 HOUR

SELECT COUNT(*) AS COUNT, case when hour(POST_DATE) >= 6
then DATE(POST_DATE)
else POST_DATE - interval 1 day
end AS NEW_POST_DATE
FROM POST
WHERE POST_DATE >= '?'
GROUP BY NEW_POST_DATE

Related

Displaying rows for this week only in PHP

I have two dates stored in my database as columns dtp_s and dtp_e (start, end). These derive from a populated form which the user is made to select a start and end date.
I want to display records from Monday - Sunday of the current week, but my current solution is showing dates from 7 Days before - Today.
SELECT id
FROM _records
WHERE
dtp_s > unix_timestamp(now() - interval 1 week)
AND userid = ?
ORDER BY dtp_s DESC
LIMIT 5
I have tried to change now() to be the value of strtotime( 'sunday' ) but this then shows no records when one does exist.
Any ideas on how I only show data based on ones that start the same week (Mon - Sun) ?
To get the Monday of the current week you could use:-
select date(curdate() - interval weekday(curdate()) day)
To add this into your code:-
SELECT id FROM _records
WHERE dtp_s > date(curdate() - interval weekday(curdate()) day) AND userid = ?
ORDER BY dtp_s DESC
LIMIT 5
After looking at other questions from SO, this can be achieved in SQL rather than mixing PHP strtotime values that could be in different timezones if not configured correctly.
SELECT id FROM _records
WHERE dtp_s > unix_timestamp(date(now() + interval 6 - weekday(now()) DAY) - interval 1 week)
AND userid = ?
ORDER BY dtp_s DESC
LIMIT 5
I am getting only the records for this week displayed.

How can I add days to a date in MYSQL in a query

I am trying to add 5 days to a date in MYSQL in a query. This is what I have done:
SELECT * FROM sales INNER JOIN partner on user_id = idpartner WHERE DATE((end_date) + 5) >= DATE(NOW()) ORDER BY end_date ASC LIMIT 0,50000
But this is not showing the list of sales which has ended. Can someone please tell me where I am making a mistake.
It looks like you want rows where end_date is later than five days ago.
The best way to get that is with
WHERE end_date >= CURDATE() - INTERVAL 5 DAY
The business of adding integers to dates doesn't work in MySQL (it's an Oracle thing). So you need to use the INTERVAL n unit syntax.
You'll notice that my WHERE clause above is functionally equivalent to
WHERE DATE(end_date) + INTERVAL 5 DAY >= DATE(NOW())
But, the first formulation is superior to the second for two reasons.
if you mention end_date in a WHERE clause without wrapping it in computations, your query can exploit an index on that column and can run faster.
DATE(NOW()) and CURDATE() both refer to the first moment of today (midnight). But CURDATE() is a bit simpler.
To fix the original query, you can use DATE_ADD with the INTERVAL keyword:
SELECT
*
FROM
sales
INNER JOIN
partner ON user_id = idpartner
WHERE
DATE_ADD(end_date, INTERVAL 5 DAY) >= DATE(NOW())
ORDER BY end_date ASC
LIMIT 0 , 50000
Said that, I wouldn't recommend applying functions such as DATE_ADD on columns, as it means that the database won't be able to use an index on end_date. Therefore, I would modify the query to:
SELECT
*
FROM
sales
INNER JOIN
partner ON user_id = idpartner
WHERE
end_date <= DATE_ADD(DATE(NOW()), INTERVAL 5 DAY)
ORDER BY end_date ASC
LIMIT 0 , 50000
As you can see, in the second alternative all functions are applied on constants and not on columns (end_date).
You can try
DATE_ADD() here is the
Link
Select DATE_ADD(DATE_FORMAT(NOW(),'%Y-%m-%d'),INTERVAL 1 DAY) FROM DUAL

mysql optimize query where date hour

Hi all, I have pretty awfull query, that needs optimizing.
I need to select all records where date of created matches NOW - 35days, but the minutes and seconds can be any.
So I have this query here, its ugly, but working:
Any optimisation tips are welcome!
SELECT * FROM outbound_email
oe
INNER JOIN (SELECT `issue_id` FROM `issues` WHERE 1 ORDER BY year DESC, NUM DESC LIMIT 0,5) as issues
ON oe.issue_id = issues.issue_id
WHERE
year(created) = year( DATE_SUB(NOW(), INTERVAL 35 DAY) ) AND
month(created) = month( DATE_SUB(NOW(), INTERVAL 35 DAY) ) AND
day(created) = day( DATE_SUB(NOW(), INTERVAL 35 DAY) ) AND
hour(created) = hour( DATE_SUB(NOW(), INTERVAL 35 DAY) )
AND campaign_id IN (SELECT id FROM campaigns WHERE initial = 1)
I assume the field "created" is a datetime field and is from the issues table? Since you don't need anything else on the issues and campaign table, then you can do the following:
SELECT e.* FROM outbound_email e
JOIN issues i ON e.issue_id = i.issue_id
JOIN campaigns c ON c.id = i.campaign_id
WHERE i.created < DATE_SUB(NOW(), INTERVAL 35 DAY)
AND c.initial = 1
There's no need to separate the datetime field into years, months...etc.
You seem to be saying you want to select all rows from a table where the time they were created was the same hour as it is currently, 35 days ago
SELECT * FROM table WHERE created BETWEEN
DATE_ADD(CURDATE(), INTERVAL (HOUR(now()) - 840) HOUR) AND
DATE_ADD(CURDATE(), INTERVAL (HOUR(now()) - 839) HOUR)
Why does it work? Curdate gives us today at midnight. We add to this the current hour of the time (e.g. Suppose it's now 5pm we'd add `HOUR(NOW()) which would give us 17, for a time now of 5pm) but we also subtract 840 because that's 35 days * 24 hours a day = 840 hours. Date add will hence add -823 hours to the current date, i.e. 5pm 35 days ago
We make the search a range to get all the records from the hour, the simplest way to specify an hour later is to subtract 839 hours instead of 840
Technically this query will also return records that are bang on 6pm (but not a second later) 35 days ago too because between is inclusive (between 1 and 10 will return 10 also
If this is a problem, change the BETWEEN for created >= blah AND created < blahblah
I haven't put the rest of your query in for reasons of clarity
As a side note, the way you did it wasn't bad- you could have simplified things by not having the year/month/day parts, just dropping the time part of the date with date(created) = date_sub(curdate(), interval 35 day) which is the year month and day combined as a date, no time element.. BUT it is generally always best to leave table data alone rather than format or convert it just to match a query. If you convert table data then indexes can no longer be used. If you go the extra mile to get your query parameters into the format of the column, and don't convert the table data then indexes on the column can be used

How to decrease SQL Query from last 30 days until now?

I am trying to get the amount of data for the last 30 days.
SELECT ( Now() - interval 1 month ),
Count(flightid) AS count
FROM flight
WHERE flightstatus = 0
AND flightvisibility = 1
AND flightvaliddate > Now()
AND flightvaliddate >= ( Now() - interval 1 month )
Right now this is working ok and it's giving me only 1 row that corresponds to the same day of last month.
What I would like is to get the remaining data from each day until now. How can I do this?
I am using MySQL.
The condition in the WHERE clause is wrong.
And since you want day wise data of last thirty days till now then you must have to use GROUP BY.
SELECT
DATE(flightvalidate) AS flightValidateDate,
Count(flightid) AS count
FROM
flight
WHERE
flightstatus = 0
AND flightvisibility = 1
AND DATE(flightvaliddate) >= CURDATE() - INTERVAL 1 MONTH
GROUP BY flightValidateDate
ORDER BY flightvalidate

Display rows from MySQL where a datetime is within the next hour

I always have trouble with complicated SQL queries.
This is what I have
$query = '
SELECT id,
name,
info,
date_time
FROM acms_events
WHERE date_time = DATE_SUB(NOW(), INTERVAL 1 HOUR)
AND active = 1
ORDER BY date_time ASC
LIMIT 6
';
I want to get up to 6 rows that are upcoming within the hour. Is my query wrong? It does not seem to get events that are upcoming within the next hour when I test it.
What is the correct syntax for this?
I'm going to postulate that you're looking at a group of records that contain a range of DATETIME values, so you probably want something more like this:
SELECT id,
name,
info,
date_time
FROM acms_events
WHERE date_time < DATE_ADD(NOW(), INTERVAL 1 HOUR)
AND date_time >= NOW()
AND active = 1
ORDER BY date_time ASC
LIMIT 6
Otherwise, your query is looking for records with a date_time of exactly "now + 1 hour". I'm assuming all your dates aren't specific to that particular second. ;)
To clarify a bit, DATE_ADD() and DATE_SUB() return exact timestamps, so your query above roughly translates to something like SELECT ... WHERE date_time = '2010-04-14 23:10:05' ORDER BY ..., which I don't think is what you want.
WHERE date_time = DATE_SUB(NOW(), INTERVAL 1 HOUR)
means date_time equals exactly now minus one hour, which would result in any record exactly one hour old.
Why not use
WHERE TIMEDIFF(date_time, NOW()) < '01:00:00'
AND date_time > NOW()