Total of all values in a day (24h) - mysql

I'd like to add all values in a database from the last 24 hours. Each value has its TimeStamp in the database.
I tried to do that with a for-loop, which adds 86400 secs (24h) every time, picks all values from one day and after that it adds all values.
Heres my code:
> `$datestart = 153839251200; //start date
for($uts = $uts; $uts > $datestart; $datestart + 86400){
if (($uts <= ($datestart + 86400)) && ($uts > $datestart)){
$uts = $datestart + 86400;
$valueFinal = $valueFinal + $value;
}
}
if($Zeitalt != $uts){
$Zeitalt=date('l, F j y H:i:s',$uts);
$uts *= 1000; // convert from Unix timestamp to JavaScript time
$data[] = array((float)$uts,(float) $valueFinal);
}`
I hope this explanation is enough, I'm not English speaking as much, otherwise just ask for more information.
Regards DR.Alfred

You've tagged this as SQL so I'm assuming an answer in SQL is what you're looking for.
Firstly, I'm not sure why you're going to the effort of using a loop to get the total when SQL has the SUM function.
I'll give you this in T-SQL as I'm not familiar with MySQL but it shouldn't be too difficult to change it to MySQL:
SELECT
SUM(YourValue)
FROM
YourTable
WHERE
YourTimeStamp > getdate() - 1
I think the MySQL equivalent of GETDATE() is NOW().

Related

Selecting rows that are within 2 hours from current time

I am using PHP with MySQL and would like to select rows that have a booking time within 2 hours from now. How do I compare what is in my database with the NOW() MySQL function?
I have columns pickupDate in the format yyyy-mm-dd and pickupTime in the format HH:mm (24-hour). I have tried creating a query with NOW() which returns the a 12-hour time as HH:mm:ss e.g. 2019-05-24 07:54:06 . I can't figure out how to format this to 19:54, or if I should use a different function instead.
For example, if the current date and time is 24/05/19 19:54:06, I would like to select rows between 19:54 and 21:54 on this date.
My table structure is:
referenceNo VARCHAR(100)
pickupDate DATE
pickupTime VARCHAR(100)
You need to create a DATETIME compatible value out of your pickupDate and pickupTime (which you can do by CONCATing them together), then you can compare that with a time range from NOW() to 2 hours later:
SELECT *
FROM yourtable
WHERE CONCAT(pickupDate, ' ', pickupTime) BETWEEN NOW() AND NOW() + INTERVAL 2 HOUR
Demo on dbfiddle
To add two hours in php
$hoursnow = date('H:i');
$timestamp = strtotime(date('H:i')) + 60*60*2;
$plusTwohours = date('H:i', $timestamp);
And $PlusTwohours using this variable frame the query like below
Sql Query:
$sqlQuery = 'select * from foodorder where pickupDate=DATE(NOW()) AND pickupTime>='.$hoursnow.' and pickupTime<='.$plusTwohours;
$result = mysql_query($sqlQuery);
variable $result will have the values of query
For Second Scenario: Adding hours to end of the day May 24 23:30:00
This should be handle by two different date for same column pickupDate
$d = new DateTime('2011-01-01 23:30:30');
$startDate = $d->format('Y-m-d H:i:s'); // For testing purpose assigned manually
$starttime = date('H:i');
// Here Process start, storing end date by adding two hours
$enddate1 = strtotime($startDate) + 60*60*2;
$enddate = date('Y-m-d', $enddate1); // Extracting date alone
$endtime = date('H:i', $enddate1); // Extracting time alone
Have to compare start and end date for column pickupDate, here is the query
$sqlQuery = "select * from foodorder where pickupDate>=DATE(".$startDate.") AND pickupDate<=DATE(".$enddate.") AND pickupTime>='".$starttime."' AND pickupTime<='".$endtime."'";
$result = mysql_query($sqlQuery);

MYsql - Get average time between a start and stop time across many rows

I have the following SQL and PHP that doesnt seem to be giving me the right numbers. (VERY high numbers)
I have a lot of rows with a start time and an end timestamp.
Im looking to get the average time between those two times.
Ie: 2 hours, 3 minutes, 46 seconds.
This is what I have.
SELECT AVG(tmp.dd) AS timetook
FROM
( SELECT TIME_TO_SEC(TIMEDIFF(timeclosed, timeanswered)) AS dd
FROM logs
WHERE timeclosed > DATE_SUB(NOW(), INTERVAL 1 DAY)
) tmp;
Am I going about this the completely wrong way? Anything obviously wrong here?
while($row = $result->fetch_assoc()) {
$timetoclose = $row['timetook'];
$hours = floor($timetoclose / 3600);
$mins = floor($timetoclose / 60 % 60);
$secs = floor($timetoclose % 60);
$timetoclose = sprintf('%02d Hour(s), %02d Minute(s), %02d Second(s)', $hours, $mins, $secs);
}
Cheers
G
SELECT SUM(TIMESTAMPDIFF(minute, start_time, end_time)) / COUNT(*) AS avg_minutes
FROM your_table
try this query.

Best Way to Store Time in Format HH:MM in MySQL for Performance

I am storing departure and arrival times as minutes(int) in database.
id, transport_date, departure_time, arrival_time
'3','2017-08-01', '620', '650'
and convert the minutes to time in JS:
e.g:
public String getDepartureTime() {
return minuteToTime(departureTime);
}
public static String minuteToTime(int minute) {
int hour = minute / 60;
minute %= 60;
String p = "AM";
if (hour >= 12) {
hour %= 12;
p = "PM";
}
if (hour == 0) {
hour = 12;
}
return (hour < 10 ? "0" + hour : hour) + ":" + (minute < 10 ? "0" + minute : minute) + " " + p;
}
and this returns 620 to "10:20 AM". Is this a good approach to store time in database? or should I just change column datatype as varchar and save time as 10:20 AM? Which way is faster, or has better performance?
Instead of storing times in INT type or Varchar, you should use "datetime" data type for those columns and while retrieving we can extract time from these column with functions.
Ex : Assuming that you have altered the datatypes to 'datetime' and your query will be
SELECT id, transport_date, Time(departure_time) As DepartureTime , Time(arrival_time) As ArrivalTime
FROM Transport_TABLE;
The way I do it, is storing a column of type DATETIME, but concatenating a fictitious date. E.g. 2018-01-01 13:05:00 (all years have a 1st January).
Then when i want to get the time with a query I use the function DATE_FORMAT
E.g:
`SELECT DATE_FORMAT(MyColDateTime, '%H:%i:%s') TIME`
Or also when I'm working with php, i use:
`$date = new DateTime('MyColDateTime');`
`$time = $date->format('H:i:s');`
The way of store in DATETIME , is useful because it gives you the possibility, to use all the functions to work both in Mysql and in your programming language.

SQL(mysql) comparing times not working

I am trying to select the message from a row where the start and end time is the same as $a and $b. But it does not bring any results however when i remove the end time it brings all the results.
I dont understand why its not working.
$a = '16:50:00';
$b = '17:00:00';
echo $times;
$query1 = ("SELECT message FROM db WHERE DATE(starttime) >= '$a' AND DATE(endtime) <= '$b'");
As you say the starttime and endtime columns are of type TIME. Running a DATE() on them will really mess the time up.
SELECT DATE('17:00:00);
will return 2017-00-00 i.e the best date it can make out of a time. Which of course is no use to you at all.
So mod your query to
SELECT message FROM db WHERE starttime >= '$a' AND endtime <= '$b'

Mysql query for within a specific date

I need to retrieve data from within a specific date range.Anybody can help me to create a query to getting the information within date range 12-12-2009 to 12-15-2009 from a mysql table.(including 12 and 15)
SELECT * FROM foo WHERE timestamp BETWEEN "2009-12-12" AND "2009-12-15"
Use this function in php first
function ChangeDateforDB($inputdate) {
if($inputdate>0) {
$month = substr($inputdate,0,2);
$date = substr($inputdate,3,2);
$year = substr($inputdate,6,4);
$show = $year."-".$month."-".$date;
return $show;
}
}
After that you can use this in query like this in the checking condition,
checkdate >= '".ChangeDateforDB($fromdate)."' and checkdate <= '".ChangeDateforDB($todate)."'
Check this one, you can get the correct answer.
SELECT ... WHERE DATEDIFF('2009-12-15',yourdatefield) <= 3 ...