SQL Select Count Column Between two Times - sql

I have the database where I have two columns - date (incl. time) and minutes - as follows:
Open_Time Minute
2013-01-01 09:00:00.000 1
2013-01-01 09:01:00.000 1
2013-01-01 09:02:00.000 1
2013-01-01 09:03:00.000 1
2013-01-01 09:04:00.000 1
2013-01-01 09:05:00.000 1
How to count the minutes between the first and last date time?
select COUNT(Minute)
from test_table
where open_time between '2013-01-01 09:00:00.000' and '2013-01-01 09:05.000'
does not work for me.
I will need to count the minutes as current time - open time in the future.
Thank you for any feedback!

for mysql may be can use :
SELECT TIMESTAMPDIFF(MINUTE,'2013-01-01 09:00:00.000','2013-01-01 09:05.000') ; // return result as minutes
read here : http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html

The SQL looks fine although it returns 6. Did you want that or did you want 5? You could always just start your SELECT criteria from 09:01:00.000 if that's what you want.
SQLfiddle here: http://sqlfiddle.com/#!2/d3f13/2

I am not getting exactly what you want. But if want to extract minute from your date then use following query.
SELECT EXTRACT(MINUTE FROM Open_Time) FROM test_table;
SELECT EXTRACT(MINUTE FROM Open_Time)-10 FROM test_table;
Above query will give only difference in minute. so check you DAY,HOUR,MINUTE,SECONDS based on your criteria

In sql server you can use DATEDIFF function,wich accept folowing parameters:
DATEDIFF(datepart,startdate,end date) and returns count(int) between specified date boundaries for selected datepart,so you could use something like this:
select DATEDIFF(mi,MIN(opentime),MAX(opentime)) AS 'minutes'
from test_table
where open_time between '2013-01-01 09:00:00.000' and '2013-01-01 09:05.000'
You also cloud count minutes from column "minutes",but it will be very hard to count them with current date(unless,every time when counting you insert current time in the table,or create temp table) !

Related

How to convert date to the date of the Monday of the date in SQL?

Assume 2022-10-01 and 2022-10-8 are Monday, and the original table looks like this:
Date
Value
2022-10-03
x
2022-10-04
y
2022-10-09
z
I want to convert it to
Date
Value
2022-10-01
x
2022-10-01
y
2022-10-08
z
Is there any simple ways to do this? Thanks!
I tried look up but seems not finding anything neat solutions
You can use the date_trunc function. For example:
SELECT date_trunc('week', dt)
FROM (
VALUES DATE '2022-12-01'
) t(dt)
output:
_col0
------------
2022-11-28
(1 row)
You want to truncate the date. This will depend on your SQL dialect, but you tagged Presto so I looked it up in their documentation.
I think you want
SELECT
truncate_date(week, Date) + interval '1' day AS date,
Value
FROM
table
(I've hedged a bit here and added a day, because I assumed it will truncate to the preceding Sunday. Do experiment with that!)

How to retrieve data within a 6 day time period

I want to retrieve the data between a 6 day time period.
The output I want is:
Date
--------
2019-05-01
2019-05-04
2019-06-01
2019-06-06
2019-07-01
This is my query so far:
select date from data d
where CAST(d.createdate as Date) between CAST('2019-05-01' as Date)
AND DATEADD(CAST(dd,6,'2016-07-01') as Date)
Why is this not retrieving the results I want?
You have several problems with your query.
The first is with your DATEADD statement which is all mixed up. You are not nesting the casted date into the statement properly. This is the corrected version:
DATEADD(dd, 6, CAST('2016-07-01' as Date))
The second is that your select projection refers to the column date which does not exist. Instead, you probably want your createdate column.
The third is that your between clause is back to front. You are saying between 2019-05-01 and 2016-07-01 but the smaller date must come first.
In fact, your given example is incorrect. In your question, you say "want to retrieve the data between two dates only for 6 days." So, why would you start with a date in 2016 and then jump to a date in 2019 and add 6 days to the date in 2019? If you want to use the DATEADD approach, you need to use the same date in both positions.
So here is your corrected query:
select d.createdate from data d
where CAST(d.createdate as Date) between CAST('2019-05-01' as Date)
AND DATEADD(dd, 6, CAST('2019-05-01' as Date))

Find the minute difference between 2 date time

I need to get the difference between 2 date time in minutes(Time difference in minutes). And the last difference will be calculated based on 6 PM of every date.
Sample data: need result of last column
User_Name Date Time difference in minutes
User 1 1/1/06 12:00 PM 30
user 2 1/1/06 12:30 PM 315
user 3 1/1/06 5:45 PM 15
Here the date will be always in same date and the last user date difference calculated based on default value 6PM. Assuming the dates of any user will not cross 6PM time.
Please suggest how to write the query for the same.
You could use the lead window function.
I assume your table is called mytable and the date column is mydate (it is a bad idea to call a column Date as it is a reserved word).
select user_name,
round((lead(mydate, 1, trunc(mydate)+18/24)
over (partition by trunc(mydate) order by mydate)
- mydate) *24*60) as difference
from mytable
I found the solution.. if its not correct let me know
SELECT User_name,created_date,
trunc(to_number((cast(nvl(lead (created_date,1) OVER (ORDER BY created_date),TRUNC(SYSDATE) + (19/24)) as date) - cast(created_date as date)))*24*60) as difference
FROM users;

Need hours difference in SQL query

Looking for a query which can retrieve the time difference of two times. Below is the example:
EmpID EmpOnTime EmpOffTime
1 2:45 3:00
2 1:00 4:00
3 1:35 2:55
4 2:45 3:20
Result should be:
For EmpID 1 Time diffrence: 0:15
For EmpID 2 Time diffrence: 3:00
For EmpID 3 Time diffrence: 1:20
For EmpID 4 Time diffrence: 0:35
I am using the following query which giving wrong result
Query:
select offTime, onTime, (strftime('%s',offTime) - strftime('%s',onTime)) / 60 AS diffrence
from emplyoee;
This one was trickier than initially thought. Here is the SQL you will need, however your input data will need to be formatted differently to get it to work.
select EmpId,
offTime,
onTime,
time(((strftime('%s', offTime) - strftime('%s', onTime)) / 60), 'unixepoch') as difference
from employee;
I had to store the data in the YYYY-MM-DD HH:MM:SS:
2019-07-18 03:00:00
Otherwise SQLite gets confused if you mean am or pm, and the %s cannot calculate since it returns the number of seconds since 1970-01-01.
I think you can use this:
SELECT
EmpID,
time(
julianday("2000-01-01 00:00:00") +
julianday(substr("0" || EmpOffTime || ":00", 1, 8)) -
julianday(substr("0" || EmpOnTime || ":00", 1, 8))) As diff
FROM
yourTable
[SQL Fiddle Demo]
Your times need to complete with :00 at the end and sometimes with 0 at the beginning that I handle it with substr("0" || yourTime || ":00", 1, 8), then by using julianday() you can find differences of two date, and also I add julianday("2000-01-01 00:00:00") to difference to get make a valid value of time and so on.

Time range- Sql

please help me with my problem. So, I have a table named 'RATES' which contains these columns:
id (int)
rate (money)
start_time (datetime)
end_time(datetime)
example data:
1 150 8:00am 6:00pm
2 200 6:00pm 4:00am
3 250 8:00am 4:00am (the next day)
What I have to do is to select all the id(s) to where a given time would fall.
e.g given time: 9:00 pm, the output should be 2,3
The problem is I got this time range between 8am to 4am the next day and I don't know what to do. Help, please! thanks in advance :D
Assuming that #Andriy M is correct:
Data never spans more than 24 hours
if end_time<=start_time then end_time belongs to the next day
then what you're looking for is this:
Declare #GivenTime DateTime
Set #GivenTime = '9:00 PM'
Select ID
From Rates
Where (Start_Time<End_Time And Start_Time<=#GivenTime And End_Time>=#GivenTime)
Or (Start_Time=End_Time And Start_Time=#GivenTime)
Or (Start_Time>End_Time And (Start_Time>=#GivenTime Or End_Time<=#GivenTime))
I don't really ever use MS SQL, but maybe this will help.
I was going to suggest something like this, but by the way you have your data set up, this would fail.
SELECT id FROM RATES
WHERE datepart(hh, start_time) <= 9 AND datepart(hh, end_time) >= 9;
You'll have you search using the actual date if you expect to get the correct data back.
SELECT id FROM RATES
WHERE start_time <= '2011-1-1 9:00' AND end_time >= '2011-1-1 9:00';
This may not be exactly correct, but it may help you look in the right direction.
I guess #gbn is not going to help you. I will try and fill in.
Given -- a table called timedata that has ranges only going over at most one day
WITH normalized AS
(
SELECT *
FROM timedata
WHERE datepart(day,start_time) = datepart(day,endtime)
UNION ALL
SELECT id, rate, start_time, dateadd(second,dateadd(day,datediff(day,0,end_time),0),-1) as end_time
FROM timedata
WHERE not (datepart(day,start_time) = datepart(day,endtime))
UNION ALL
SELECT id, rate,dateadd(day,datediff(day,0,end_time),0) as start_time, end_time
FROM timedata
WHERE not (datepart(day,start_time) = datepart(day,endtime))
)
SELECT *
FROM normalized
WHERE datepart(hour,start_time) < #inhour
AND datepart(hour,end_time) > #inhour
This makes use of a CTE and a trick to truncate datetime values. To understand this trick read this question and answer: Floor a date in SQL server
Here is an outline of what this query does:
Create a normalized table with each time span only going over one day by
Selecting all rows that occur on the same day.
Then for each entry that spans two days joining in
Selecting the starttime and one second before the next day as the end time for all that span.
and
Selecting 12am of the end_time date as the starttime and the end_time.
Finally you perform the select using the hour indicator on this normalized table.
If your ranges go over more than one day you would need to use a recursive CTE to get the same normalized table.