mysql time select where compare - mysql

mysql datetime select problem.
my table check_time:
count = 1
start = 23:57:45
end = 00:02:10
count = 2
start = 00:02:45
end = 00:07:10
i tried this query:
select count
from check_time
where start <= DATE_FORMAT(now(), '%H:%i:%s')
and end >= DATE_FORMAT(now(), '%H:%i:%s');
i want the now() = "23:57:45" between "00:02:10" select -> count = 1
not working on count 1 only.
but working perfectly other count 2~100..
sorry for my bad english.

A great deal depends on how you have actually defined the columns start and end. I have assumed they are "time" columns in the following.
Also note that to avoid the problem of using the server time which I could not control I have used #curtime but in your code you should use CURTIME() instead. See the demonstration demonstration at SQL Fiddle
CREATE TABLE check_time
(`count` int, `start` time, `end` time)
;
INSERT INTO check_time
(`count`, `start`, `end`)
VALUES
(1, '23:57:45', '00:02:10'),
(2, '00:02:45', '00:07:10')
;
Query 1:
set #curtime:= cast('23:57:45' as time)
select
*
, #curtime
from check_time
where (
(`start` < `end` and #curtime between `start` and `end`)
OR (`start` > `end` and
(#curtime between `start` and cast('24:00:00' as time) )
OR (#curtime between cast('00:00:00' as time) and `end` )
)
)
Results:
| count | start | end | #curtime |
|-------|----------|----------|----------|
| 1 | 23:57:45 | 00:02:10 | 23:57:45 |
Query 2:
set #curtime:= cast('00:02:45' as time)
select
*
, #curtime
from check_time
where (
(`start` < `end` and #curtime between `start` and `end`)
OR (`start` > `end` and
(#curtime between `start` and cast('24:00:00' as time) )
OR (#curtime between cast('00:00:00' as time) and `end` )
)
)
Results:
| count | start | end | #curtime |
|-------|----------|----------|----------|
| 2 | 00:02:45 | 00:07:10 | 00:02:45 |

Related

Updating mysql trigger

I have a table schedules with these columns
id
start_time
end_time
per_user_time
number_of_visitors
every time new entry is created I want to calculate the minutes interval between the start_time and end_time and divide by the minutes of per_user_time and insert into the number_of_visitors column using trigger
here is what I have for the calculation and is working correctly but how to insert into number_of_visitors
DB::unprepared('CREATE TRIGGER update_number_of_patients BEFORE INSERT ON `schedules` FOR EACH ROW
BEGIN
SET NEW.number_of_patients =
(SELECT #minutes := (TIME_TO_SEC(`end_time`) - TIME_TO_SEC(`start_time`))/60 AS `minutes`, #interval:= TIME_TO_SEC(`per_patient_time`)/60 AS `interval`, #minutes / #interval AS `patients` FROM schedules)
END
');
Thank you for your time
This is the sample of my desired result
id | start_time | end_time | per_user_time | minutes | interval number_of_visitors
1 | 08:00:00 | 13:00:00 | 00:30:00 | 300 | 30 | 10
Note
I don't have minutes and interval columns I got them from the query.
I hope you understand my question.
I finally manage to get it work. this is how I did it
DB::unprepared('CREATE TRIGGER update_number_of_patients_before_insert BEFORE INSERT ON `schedules` FOR EACH ROW
BEGIN
SET #minutes = (SELECT (TIME_TO_SEC(NEW.end_time) - TIME_TO_SEC(NEW.start_time))/60 FROM `schedules` LIMIT 1);
SET #interval = (SELECT TIME_TO_SEC(NEW.per_patient_time)/60 FROM `schedules` LIMIT 1);
SET NEW.number_of_patients = #minutes / #interval;
END
');

Calculate total ON time from ON OFF timestamps

I have a table containing alternating ON & OFF events with its timestamp. How do i calculate total time between each ON & OFF?
Status Timestamp
============================
ON 2019-01-01 07:00:00
OFF 2019-01-01 08:30:00
ON 2019-01-01 09:00:00
OFF 2019-01-01 10:00:00
ON 2019-01-01 10:30:00
OFF 2019-01-01 11:30:00
Consider the following...
CREATE TABLE my_table
(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
dt DATETIME NOT NULL,
status VARCHAR(5) NOT NULL
);
INSERT INTO my_table VALUES
(1,'2015-01-01 13:00:00','ON'),
(2,'2015-01-01 13:10:00','OFF'),
(3,'2015-01-01 13:20:00','ON'),
(4,'2015-01-01 13:30:00','OFF'),
(5,'2015-01-01 13:35:00','ON'),
(6,'2015-01-01 13:40:00','OFF'),
(7,'2015-01-01 13:50:00','ON'),
(8,'2015-01-01 15:00:00','OFF');
SELECT x.*,
TIMEDIFF(MIN(y.dt),x.dt) AS TimeDiff
FROM my_table AS x
INNER JOIN my_table AS y ON y.dt >= x.dt
WHERE x.status = 'ON' AND y.status = 'OFF'
GROUP
BY x.id;
Refer DB FIDDLE For More:
https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=00dc040da540f852f08b2f02750bc16d
CREATE TABLE events (
`status` VARCHAR(3),
`timestamp` VARCHAR(19)
);
INSERT INTO events
(`status`, `timestamp`)
VALUES
('ON', '2019-01-01 07:00:00'),
('OFF', '2019-01-01 08:30:00'),
('ON', '2019-01-01 09:00:00'),
('OFF', '2019-01-01 10:00:00'),
('ON', '2019-01-01 10:30:00'),
('OFF', '2019-01-01 11:30:00');
SELECT
TIME_FORMAT(SEC_TO_TIME(TIME_TO_SEC(
SUM(TIMEDIFF(offtime, ontime))
)), '%H:%i')
AS total FROM (
SELECT e.timestamp AS offtime, (SELECT timestamp
FROM events AS st WHERE st.timestamp < e.timestamp AND st.status = "ON"
ORDER BY st.timestamp DESC LIMIT 1) AS ontime
FROM events AS e WHERE e.status='OFF') AS onoffs
Selects every OFF record, joins the most recent ON record to it, sums time ranges. With your data it gives the result: total 03:30
Doesn't account for open ranges. E.g. if the data series is started with OFF; or if it ends with ON, the time up to current moment would not be counted.
https://www.db-fiddle.com/f/hr27GhACxGd7ZvFaa52xiK/0#

mysql query to find that time is between from and to time

I have a from_time an to_time in my table.
one of the record is from_time: 19:00:00 and to_time: 01:30:00
if user select 12:30 AM or 11:00 PM.
how do i correctly find that it is between from_time and to_time.
Mysql query i tried:
SELECT * FROM `table` WHERE '19:00:00' >= from_time and '19:00:00' <= to_time
is not working.
You used value instead of column name
You can use as below query. You can change value as per your need.
Change Time value as per your need first.
First Option with Where
SELECT * FROM `table` WHERE from_time >= '00:00:00' and to_time <= '23:59:59'
Second option is between
SELECT * FROM `table` WHERE from_time between '00:00:00' and '23:59:59'
Your question does not show where the selected time is coming from. Is it in a column, is it something that the user sets in the SQL or is it sent through code?
If the time is set in the SQL then the way to do this is as follows:
SET #mytime := '19:00:00';
SELECT * FROM `table` WHERE CAST(#mytime AS TIME) BETWEEN from_time AND to_time;
where #mytime is the user set variable and assuming that from_time and to_time are time format.
My test table for the above was as follows:
CREATE TABLE `timetest` (
`id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`from_time` time DEFAULT NULL,
`to_time` time DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
with test data as:
INSERT INTO `timetest` (`id`, `from_time`, `to_time`) VALUES
(1, '09:00:00', '11:00:00'),
(2, '06:30:00', '14:00:00'),
(3, '14:29:10', '16:12:18'),
(4, '09:11:17', '23:00:01'),
(5, '18:00:00', '23:59:59'),
(6, '01:12:00', '11:59:44');
For to_times which go over midnight you could add 24hours and then test. For example
drop table if exists t;
create table t(from_time time, to_time time);
insert into t values
('18:00:00','20:00:00'),
('18:00:00','01:00:00'),
('16:00:00','18:00:00');
select from_time,to_time,
case when '19:00:00' between
from_time and
if(to_time < from_time,
addtime(to_time,'24:00:00'),
to_time)
then 'true'
else 'false'
end as truefalse
from t;
+-----------+----------+-----------+
| from_time | to_time | truefalse |
+-----------+----------+-----------+
| 18:00:00 | 20:00:00 | true |
| 18:00:00 | 01:00:00 | true |
| 16:00:00 | 18:00:00 | false |
+-----------+----------+-----------+
3 rows in set (0.00 sec)

Select between date range ignoring the year

I have a table that stores opening dates in 2 columns with the type Date. I need to select the entries which are open during a date range, but without taking the year in regard.
To prevent confusion I'll write all dates in the format YYYY-MM-DD or MM-DD.
Here's a simple example for the table.
| ID | Start | End |
| 1 | 2014-12-01 | 2014-12-31 |
| 2 | 2015-11-18 | 2016-01-20 |
| 3 | 2015-01-01 | 2016-01-18 |
| 4 | 2015-12-10 | 2015-12-20 |
Based on this post I'm able to look for entries that are in the same year. This query for example would give me the rows 1 and 4 if I'm looking for anything open between 12-13 and 12-15.
SELECT *
FROM Dates
WHERE
DATE_FORMAT(Start, "%m%d") <= DATE_FORMAT("2015-12-13", "%m%d") AND
DATE_FORMAT(End, "%m%d") >= DATE_FORMAT("2016-12-15", "%m%d")
Looking for entries between 12-01 and 01-13 won't work with this though.
Does anybody have an idea how I'd be able to do this?
Edit
Just so everybody interested has the testing table.
CREATE TABLE `Dates` (
`idDates` int(11) NOT NULL AUTO_INCREMENT,
`Start` date DEFAULT NULL,
`End` date DEFAULT NULL,
PRIMARY KEY (`idDates`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
INSERT INTO `Dates`
(`idDates`,
`Start`,
`End`)
VALUES
('1', '2014-12-01', '2014-12-31'),
('2', '2015-11-18', '2016-01-20'),
('3', '2015-01-01', '2016-01-18'),
('4', '2015-12-10', '2015-12-20');
Let me assume that you have two variables: #StartDate and #EndDate. Then you can write the logic as:
SELECT *
FROM Dates
WHERE (DATE_FORMAT(#StartDate, '%m%d') <= DATE_FORMAT(#EndDate, '%m%d') AND
DATE_FORMAT(Start, '%m%d') <= DATE_FORMAT(#StartDate, '%m%d') AND
DATE_FORMAT(End, '%m%d') >= DATE_FORMAT(#EndDate, '%m%d')
) OR
(DATE_FORMAT(#StartDate, '%m%d') > DATE_FORMAT(#EndDate, '%m%d') AND
DATE_FORMAT(Start, '%m%d') > DATE_FORMAT(#StartDate, '%m%d') AND
DATE_FORMAT(End, '%m%d') < DATE_FORMAT(#EndDate, '%m%d')
);

decrease/increase between date in mysql or oracle SQL

I've problem in query mysql
I want to find hour per date between 2 date divided by day
for example,
I have startdate 14/12/2014 09:00:00AM , and enddate 17/12/2014 03:30:00AM
I want to result like this
14/12/2014 - 15 hour
15/12/1014 - 24 hour
16/12/2014 - 24 hour
17/12/2014 - 3,5 hour
Is that possible in a MySQL or Oracle SQL query?
Finally, I have found the query for oracle sql...
THANKS FOR YOUR HELP
SELECT
TO_DATE (START_DATE + COLUMN_VALUE - 1, 'DD/MM/YYYY') AS THE_DATE,
CASE
WHEN TO_DATE (START_DATE, 'DD/MM/YYYY') = TO_DATE (END_DATE, 'DD/MM/YYYY')
THEN (END_DATE - START_DATE)*24
WHEN (START_DATE + COLUMN_VALUE - 1) = START_DATE
THEN (23 - TO_CHAR (START_DATE, 'HH24')) + ((60 - TO_CHAR (START_DATE, 'MI'))/60) + ((360 - TO_CHAR (START_DATE, 'SS'))/360)
WHEN TO_DATE (START_DATE + COLUMN_VALUE - 1, 'DD/MM/YYYY') <> TO_DATE (END_DATE, 'DD/MM/YYYY')
THEN 24
ELSE TO_CHAR (END_DATE, 'HH24') +
(TO_CHAR (END_DATE, 'MI')/60) +
(TO_CHAR (END_DATE, 'SS')/360) END
FROM MY_TABLE,
TABLE( CAST( MULTISET (
SELECT
LEVEL L
FROM DUAL
CONNECT BY LEVEL <= END_DATE - START_DATE + 1) AS SYS.ODCINUMBERLIST))
Use MySQL TIMESTAMPDIFF or Oracle EXTRACT function to calculate difference between two value fields of Datetime type (2nd and 3rd parameters). 1st parameter passed is your selected measurement to count the difference. This could be HOUR, MINUTE, SECOND, DAY etc.
SELECT
`startdate` AS `date`,
TIMESTAMPDIFF(
HOUR,
`startdate`,
`enddate`) AS `hours_delta`
FROM my_table
The result would be:
___date_______hours_delta____
14/12/2014________66________
15/12/1014________..._________
SQL Fiddle
Oracle 11g R2 Schema Setup:
CREATE TABLE MY_TABLE ( ID, START_DATE, END_DATE ) AS
SELECT 1, TO_DATE( '14/12/2014 09:00:00AM', 'DD/MM/YYYY HH:MI:SSAM'), TO_DATE( '17/12/2014 03:30:00AM', 'DD/MM/YYYY HH:MI:SSAM') FROM DUAL
UNION ALL SELECT 2, TO_DATE( '20/12/2014 09:00:00AM', 'DD/MM/YYYY HH:MI:SSAM'), TO_DATE( '20/12/2014 03:30:00PM', 'DD/MM/YYYY HH:MI:SSAM') FROM DUAL
Query 1:
WITH Differences AS (
SELECT ID,
TRUNC( START_DATE ) AS Day,
LEAST(
TRUNC( START_DATE ) + INTERVAL '1' DAY,
END_DATE
) - START_DATE AS Diff
FROM MY_TABLE
UNION
SELECT ID,
COLUMN_VALUE,
CASE WHEN COLUMN_VALUE < TRUNC( END_DATE )
THEN 1
ELSE END_DATE - COLUMN_VALUE
END
FROM MY_TABLE,
TABLE( CAST( MULTISET (
SELECT TRUNC( START_DATE ) + LEVEL
FROM DUAL
WHERE TRUNC( START_DATE ) + LEVEL <= TRUNC( END_DATE )
CONNECT BY
TRUNC( START_DATE ) + LEVEL <= TRUNC( END_DATE )
) AS SYS.ODCIDATELIST ) )
)
SELECT ID,
TO_CHAR( Day, 'YYYY-MM-DD' ) AS Day,
TO_CHAR( TO_NUMBER( Diff * 24 ), '99D90' )
|| ' hour ' AS Hours
FROM DIFFERENCES
Results:
| ID | DAY | HOURS |
|----|------------|--------------|
| 1 | 2014-12-14 | 15.00 hour |
| 1 | 2014-12-15 | 24.00 hour |
| 1 | 2014-12-16 | 24.00 hour |
| 1 | 2014-12-17 | 3.50 hour |
| 2 | 2014-12-20 | 6.50 hour |