mysql retrieve difference between current and last hour - mysql

For the below table, i would like to get the difference between last hour and current hour for col-D and col-E for each of the site.
As part of that I am trying to first get the latest (current) hour entries for each of the site, but the following query is only listing me the entries with endTime as 01:00:00, when i have entries upto 9.00AM
select distinct(mmeName), endDate, endTime, c_ratio, set_time from attach where
type='INIT' and Date(endDate)=curDate() and
Time(endTime) >= DATE_ADD(Time(endTime), INTERVAL -1 HOUR) group by mmeName;
Any help would be appreciated for the immediate issue and as well finding the difference between current and last hour.

EDITED
I think this is what you are looking for. This will give you any records where the endTime is one hour prior to the latest current time for each mmeName. The 'max' sub-select gets the latest end datetime for each mmeName, and the join back matches on record exactly one hour prior to that.
SELECT mmeName, endDate, endTime, c_ratio, set_time
FROM attach a
JOIN
(SELECT mmeName, CONCAT(endDate, ' ' , endTime) max_endDateTime
FROM attach
WHERE type = 'INIT'
ORDER BY endDate DESC, endTime DESC
) AS max ON max.mmeName = a.mmeName
AND max.max_endDateTime = DATE_ADD(CONCAT(endDate, ' ' , endTime), INTERVAL 1 HOUR)
WHERE type = 'INIT'
;
ORIGINAL
select mmeName, endDate, endTime, c_ratio, set_time
from attach
where type='INIT' and Date(endDate)=curDate() and
endTime >= DATE_SUB(now(), INTERVAL -1 HOUR)
group by mmeName;
Note: If there are multiple matching records for a given mmeName, this query will just grab one of them.
EDITED: You need drop the TIME() functions from the WHERE clause. Both would have the date and time and if you didn't, if you ran it between 12:00 AM to 1:00 AM it would not return any results.

Related

UPDATE sql to change time only in datetime

I want to UPDATE time only from datetime using sql but it seem cant work. the update will get from user and only change the time.
example 2018-10-06 08:00:00 update to 2018-10-06 12:00:00 (time that user enter)
$sql3="UPDATE course
SET date_start = '$date_start'
WHERE date_start = SUBSTRING(date_start,11,17)
AND CourseNo = '$id1' ";
$hasil3=mysql_query($sql3);
if($hasil3==false)
echo "SQL error:".mysql_error();
else
{
?> <center>
<script language="javascript">
alert("Successfully update!");window.location="studentTimetable.php";
</script>
You can use an expression such as:
select date('2018-10-06 08:00:00') + interval 12 hour
You can also use addtime() if you want to add hours/minutes/seconds.
This should be simple enough to put into an update statement if that is what you want to do.
If I understand you right, you get an input as string in the format <hours> ":" <minutes> ":" <seconds>, that represents a time of the day. You want to replace the time of the day portion of a datetime column with that given time of the day.
To do so you can first downcast the column to a date and then upcast it again to a datetime. That way the time of the day portion becomes 00:00:00. Now use date_add to add the time of the day the user has given to you. Since the time of the day was zeroed before that will result in a datetime with the time of the day as the user put in.
UPDATE elbat
SET nmuloc = date_add(cast(cast(nmuloc AS date) AS datetime), INTERVAL '12:00:00' HOUR_SECOND);
I had a similar problem to this..
I have a number of dates that are not quite right by a few seconds. They should all end on an Hour, i.e 00:00
Work out how much time I need add (I know i want to add some seconds)
SELECT 60 - DATEPART(SECOND, EndDate), e.*
FROM Events e
WHERE DatePart(SECOND, EndDate) <> 0
Now I can write an update to correct all the dates that are slightly off.
UPDATE Events
SET EndDate = DATEADD(SECOND, i.Seconds, i.EndDate)
FROM (
SELECT Id, 60 - DATEPART(SECOND, EndDate) AS Seconds, EndDate
FROM Events e
WHERE DatePart(SECOND, EndDate) <> 0
) i
WHERE
i.ID = Events.ID

Select MySQL data starting from a specific date

I have player statistics which I would like to publish from certain dates.
At the moment I can see statistics in the database from the beginning.
SELECT name,
bankmoney AS Bank,
Playerkills AS 'Player Kills',
deathcount AS Deaths ,
aikills AS 'AI Kills',
teamkills AS 'Team Kills',
revivecount AS Revives ,
capturecount AS 'Territories Captured',
LastModified AS 'Last Seen'
FROM playerinfo
JOIN playerstats
ON playerinfo.UID = playerstats.PlayerUID
ORDER BY BankMoney DESC;
But I would like to present statistics from the start of the day and the start of the week.
How would I do that ?
Based on Spitfire's comments, to get the last 24 hours of data you can use INTERVAL and go back the required number of days you want. NOW() will give you the time the query was executed and BETWEEN will allow you to search between two days. So that part of the query could be:
WHERE 'Last Seen' BETWEEN NOW() AND NOW() - INTERVAL 1 DAY;
A week would require a change from 1 day to 7.
Try it.SELECT * from table_name where a.exam_date BETWEEN $date1 AND $date2;
for example if you want to see only statistics with lastModified greater or equal today just add a where clause:
WHERE 'Last Seen' >= CURRENT_DATE()

MySQL time diff grouped by day

I have a table from which I'm trying to extracted summed timediff information grouped by days. I don't really know if this is possible
Table columns: mode_type, start_time.
A record exists in this table for each time an employee starts or stops a timer. mode_type = 1 for start, mode_type = 0 for stop.
I'd like to return a sum of the seconds used for each day in the last 30 days.
E.g:
date, seconds_used
02/04/2014, 25
03/04/2014, 12415
04/04/2014, 925
Currently I can return a list of seconds used per mode_type and date but this required later calc in PHP.
SELECT
mode_type,
Sum(Unix_Timestamp(start_time)) AS time,
start_time
FROM
activations
WHERE
start_time < Date(Now() + INTERVAL 1 MONTH)
GROUP BY
mode_type, Day(start_time)
ORDER BY
start_time
I'm stuck... is this possible or do I need to do revert to calculating the diff in PHP post request?
Thanks in advance.
Can you try with this:
SELECT DATE(start_time) AS startdate, TIME_TO_SEC(TIMEDIFF(NOW(),start_time)) AS secs
FROM activations
GROUP BY
startdate

SQL Query for reservation dates that break a month end?

I'm using a custom PHP function to produce a visual calendar for a single month that blocks out dates based on a table that contains an start date, and an duration - For example:
...This is produced by data saying that the table should be blocked out for 4 days from the 14th, and 7 days from the 27th.
The query looks something like this:
SELECT GROUP_CONCAT(DATE_FORMAT(start_date,'%d'),':', event_duration) AS info
FROM events
WHERE YEAR(start_date = '2012'
AND MONTH(start_date) = '07'
ORDER BY start_date
(You could safely ignore the group concat and return the data as individual rows, that doesn't really matter).
I'm looking for a modification to the query that would block out dates at the start of the month IF an event starts in the previous month, but its length takes it into the following.
For instance - in the above example, the event on the 27th is actually scheduled to last 7 days in the database, so if I ran the query for MONTH(start_date) = '08' I'd like to say the first two dates blocked out, which they wouldn't currently be, because the start date that would block it out is not in the month being selected.
I'm fairly sure there's a subquery or something in there to grab the rows, but I just can't think of it. Any takers?
EDIT
The answer from Salman below pointed me in the directon I wanted to go, and I came up with this as a way of getting carryovers from the previous month to show as '1st' of the month with the number of remaining days:
SELECT IF(MONTH(start_date) < '08', '2012-08-01', start_date) AS starter,
IF(MONTH(start_date) < '08', duration - DATEDIFF('2012-08-01',start_date), duration) AS duration
FROM EVENTS
WHERE YEAR(start_date) = '2012'
AND (MONTH(start_date) = '08' OR MONTH(start_date + INTERVAL duration DAY) = '08')
Obviously a lot of variables there to replace in PHP, so maybe there's an even better way?
Original Answer:
Assuming that the month in question is 2012-07, you need this query:
SELECT column1, column2, columnN
FROM `events`
WHERE `start_date` <= '2012-07-01'
AND `start_date` + INTERVAL `duration` DAY > '2012-07-01'
ORDER BY start_date
Revised Answer:
Apparently you need a query that checks for overlapping (or conflicting) dates. The example dates are 2012-07-01 through 2012-08-01 and the query is:
SELECT *
FROM events
WHERE '2012-08-01' > start_date
AND start_date + INTERVAL duration DAY > '2012-07-01'
ORDER BY start_date
To constrain the start date and interval, you can use SELECT ... CASE statement:
SELECT
CASE
WHEN start_date < '2012-07-01' THEN '2012-07-01'
ELSE start_date
END AS start_date_copy,
CASE
WHEN start_date < '2012-07-01' THEN duration - DATEDIFF('2012-07-01', start_date)
ELSE duration
END AS duration_copy,
FROM ...
The answer I was looking for, thanks to the other contributor for pointing me in the right direction and enabling me to solve it!
This is based on $yyyy and $mm coming from PHP (in my case, into a function call), and selecting individual rows rather than grouping:
SELECT start_date, duration
FROM reservations
WHERE YEAR(start_date) = '".$yyyy."'
AND MONTH(start_date) = '".$mm."'
UNION
SELECT '".$yyyy."-".$mm."-01',
duration - DATEDIFF('".$yyyy."-".$mm."-01',start_date)
FROM reservations
WHERE YEAR(start_date) = '".$yyyy."'
AND MONTH(start_date) < '".$mm."'
AND MONTH(start_date + INTERVAL duration DAY) = '".$mm."'
ORDER BY start_date

Trying to select the number of mysql rows inserted yesterday

I can normally do this but it appears my brain is not functioning well right now and I'm missing something.
Every day via a cron job that is run at 1am, I want to get a count of rows that were inserted yesterday, and the date.
ie
SELECT DATE(added) as date, COUNT(*) FROM bookings WHERE added = DATE_SUB(NOW(), INTERVAL 1 DAY) GROUP BY date
'added' contains a timestamp ie '2011-04-18 12:31:31'
What am I getting wrong here? I know there are many rows added yesterday but my query is returning 0 results and no mysql_errors :(
Any ideas?
Please try
SELECT DATE(added) as yesterday, COUNT(*) FROM bookings WHERE DATE(added) = DATE(DATE_SUB(NOW(), INTERVAL 1 DAY)) GROUP BY yesterday
or perhaps
SELECT DATE(added) as yesterday, COUNT(*) FROM bookings WHERE DATE(added) = DATE_SUB(CURDATE(), INTERVAL 1 DAY) GROUP BY yesterday
Updated
Corrected the WHERE part.
well whatever NOW() is will return the time portion and unless they were added at exactly that time the day before they wont be counted.
So either use BETWEEN and specify time range, or format the date in your query to only match on the day month year components and not time
WHERE added = does only match exact NOW() - 1 DAY, you should select by a range instead.