I have timestamp column and for the start time if my time is greater than 5:30Pm I would like to consider the time as 5:00PM and I need to subtract the converted minutes from start date and enddate.
SELECT [starttime], [endtime],
case when FORMAT([starttime],'HH:mm') >'17:30' then 17.00
end as newstarttime,
FORMAT([endtime],'HH:mm') as newendtime
FROM Table1
I tried to convert the timestamp into 24hour format but not sure about the next steps.
Starttime Endtime
2019-08-13 17:40:33:000 2019-08-13 19:00:00:000
I am assuming that you are using SQL Server, and I think you want:
select t1.*,
(case when convert(time, starttime) >= '17:30:00'
then dateadd(hour, 17, convert(datetime, convert(date, starttime)))
else starttime
end) as new_starttime
from table1 t1;
You can also express the date add logic as:
convert(datetime, convert(date, starttime)) + '17:00:00'
I have timestamp field and for the start time if my time is greater than 5:30Pm I would like to consider the time as 5:00PM
To do this, its easier to work with dates than doing character conversion. See the below query:
SELECT [starttime], [endtime]
, case
when FORMAT([starttime],'2020-01-01 HH:mm:00') > '2020-01-01 17:30:00' then '17:00'
else FORMAT([starttime],'HH:mm')
end as newsttime
, FORMAT([endtime],'HH:mm') as newendtime
FROM Table1;
What do you mean by:
I need to subtract the converted minutes from start date and enddate.
Related
I have one table named Employee in SQL Server:
Employee Clock-In Clock-Out
111 11/4/2019 2:31:08 PM 11/4/2019 4:31:08 PM
112 11/4/2019 2:31:08 PM 12/4/2019 2:31:08 PM
I wish to have a new column in this Employee table which is Duration: (below is my expected table)
Employee Clock-In Clock-Out Duration(day)
111 11/4/2019 2:31:08 PM 11/4/2019 4:31:08 PM 0
112 11/4/2019 2:31:08 PM 12/4/2019 2:31:08 PM 1
113 13/4/2019 2:31:08 PM 2
The Duration(day) column data will be auto calculate by using the Clock-Out column minus the Clock-In column; however if the Clock-Out time is empty, it will take the current datetime minus the Clock-In column. For example the current datetime is 15/4/2019 2:31:08 PM.
Anyone have ideas on this?
use datediff() and coalesce()
select employee,
ClockIn,ClockOut,
datediff(day,ClockIn,coalesce(ClockOut,getdate())) as duration
from table_name
for that you can create a view like below
create view view_name AS
select employee,
ClockIn,ClockOut,
datediff(day,ClockIn,coalesce(ClockOut,getdate())) as duration
from table_name
Use DATEDIFF, not with DAY but with MINUTE or SECOND. The following example returns 1 day but the amount of time is actually 2 seconds:
SELECT
DATEDIFF(
DAY,
'2019-01-01 23:59:59',
'2019-01-02 00:00:01')
DATEDIFF with DAY will not take into account the time portion, it will only look at the day difference.
So you can use a lower degree to measure a full day, like minutes or seconds:
DECLARE #FirstDate DATETIME = '2019-01-01 23:59:59'
DECLARE #SecondDate DATETIME = '2019-01-03 05:00:00'
SELECT
SecondDifferences = DATEDIFF(SECOND, #FirstDate, #SecondDate),
FullDaysBySecond = DATEDIFF(SECOND, #FirstDate, #SecondDate) / 86400, -- 86400 = 24*60*60
MinuteDifferences = DATEDIFF(MINUTE, #FirstDate, #SecondDate),
FullDaysByMinute = DATEDIFF(MINUTE, #FirstDate, #SecondDate) / 1440, -- 1440 = 24*60
DayDifferences = DATEDIFF(DAY, #FirstDate, #SecondDate) -- Wrong, not full 24 hours days!
Result:
SecondDifferences FullDaysBySecond MinuteDifferences FullDaysByMinute DayDifferences
104401 1 1741 1 2
So the ALTER would be:
ALTER TABLE Employee ADD Duration AS DATEDIFF(
MINUTE,
[Clock-In],
ISNULL([Clock-Out], GETDATE()))
/ 1440
You won't be able to persist this column because GETDATE() is non-deterministic and SQL Server won't let you, meaning that this will be computed every time it is queried.
use datediff() and sql server isnull() function, since your columns are with dash, you need to escape it.
select Employee
, [Clock-In]
, [Clock-Out]
, datediff(dd, [Clock-In], isnull([Clock-Out], getdate())) as Duration
from Employee
I'm trying to SELECT all the rows from a SQL database which are between an hour interval, for every day.
The datetime column is called "Dt" and has the following datetime format: 2019-10-17 16:03:43
I'd like to extract all the rows from this table where the Dt was between 22:00:00 and 02:00:00, for everyday.
SELECT *
FROM MY_TABLE
WHERE "Dt" BETWEEN '*-*- 22:00:00' AND '*-*- 02:00:00';
where * should be any...
Thanks for your support!
EDIT: I forgot to mention: I'm using the integrated SQL interpreter from DB Browser for SQLite
You need to extract the time part of the date and compare that it is within the range. Since midnight is between 22 and 2, you will need to split it to two comparisons, time between 22 and 0 and between 0 and 2.
To see how to extract the time take a look at this question.
With Postgres, assuming dt is defined as timestamp you can do the following:
SELECT *
FROM MY_TABLE
WHERE "Dt" BETWEEN "Dt"::date + time '22:00:00' and ("Dt"::date + 1) + time '02:00:00'
Or if you want to exclude timestamps at precisely 02:00:00
SELECT *
FROM MY_TABLE
WHERE "Dt" >= "Dt"::date + time '22:00:00'
and "Dt" < ("Dt"::date + 1) + time '02:00:00'
select DT_time from (
select cast (substr(to_char(Dt,'dd-mm-yyyy HH:MM:SS'),12,2) as integer ) as DT_time from MY_TABLE )
where DT_time between 2 and 22;
between 22:00:00 and 02:00:00
means:
SELECT *
FROM MY_TABLE
WHERE
substr(Dt, 12) BETWEEN '22:00:00' AND '23:59:59'
OR
substr(Dt, 12) BETWEEN '00:00:00' AND '02:00:00'
This will work ::
SELECT *
FROM MY_TABLE
WHERE DATEPART(HOUR, Dt)>22
AND DATEPART(HOUR, Dt)<2
Update :
SELECT *
FROM MY_TABLE
WHERE Dt Between DATEADD (hour,22,DATEADD(day, DATEDIFF(day, 0, Dt), 0)) AND DATEADD (hour,2,DATEADD(day, DATEDIFF(day, -1, Dt), 0))
SELECT *
FROM MY_TABLE
WHERE DATEPART(HOUR, Dt)>22
OR DATEPART(HOUR, Dt)<2
Above query work for you..
1st one will check only for particular date and consecutive next date along with your time range.
But If you don't care about dates and only looking for time interval in particular hours then 2nd one is for you.
For SQLite :
SELECT *
FROM MY_TABLE
WHERE strftime('%H','Dt')>22
OR strftime('%H','Dt')<2
The below query returns MINUTE of certain hour of a date.
For example if date value ='2017-07-19 05:50:00.000', it will returns 50.
My issue is I need to get MINUTE in specified date not all the dates that exist in the table.
Query:
SELECT
DATEPART(MINUTE, ClockOut)
FROM
[dbo].[Attendance]
WHERE
DATEPART(HOUR, ClockOut) = '5'
The query I tried to return minutes only in '2017-07-19' and it returns no record.
SELECT
DATEPART(MINUTE, ClockOut)
FROM
[dbo].[Attendance]
WHERE
DATEPART(HOUR, ClockOut) = '5' AND ClockOut = '2017-07-19'
Sample data
Clock Out
2017-07-19 05:50:00.000
2017-07-20 05:51:00.000
2017-07-21 05:52:00.000
I need to return minutes at hour 5 only on this date '2017-07-19'
You are comparing datetime to date that's why it is not returning your desired result.
SELECT DATEPART(MINUTE, ClockOut)
FROM [dbo].[Attendance]
WHERE DATEPART(HOUR, ClockOut) = '5'
AND CAST(ClockOut AS DATE) = '2017-07-19';
If you use ClockOut='2017-07-19' it's like write '2017-07-19 0:00:00'. Try to use DataPart (yyyy, Clockout)=2017 and DataPary (MM, Clockout)=7 and DataPart (dd, Clockout)=19
Your ClockOut columns contains a DateTime (2017-07-19 12:03:42) so it's value is never exact equal to a date (2017-07-19). Use a range instead so the Query Plan can use an potential index on Clockout. Casting to a Date or using DatePart rules this out causing longer execution times if the number of rows is large.
SELECT DATEPART(MINUTE, ClockOut)
FROM [dbo].[Attendance]
WHERE DATEPART(HOUR, ClockOut) = 5
AND ClockOut BETWEEN '2017-07-19'
AND '2017-07-20' -- start of next day
working demo
I have three Shifts in my office.How i can get name of current running shift using Sql Query ?
Table Description is as given below
Id, Name, startTime, hours
1, Shift1, 7:00 am, 8
2, Shift2, 3:00 pm, 8
3, Shift3, 11:00 pm, 8
Thanks in Advance
This is quite a top-level question, so I'm going to give you a top-level answer, rather than writing the code for you, because that way you'll have the tools to solve other problems in future.
I would approach this in 3 stages:
Write a query that selects the end time of each shift based on the startTime and hours columns, i.e. "what time is X hours after time Y". The exact function to use depends which DBMS you use (MySQL, PostgreSQL, MS SQL Server, SQLite, etc), but is likely to be called something like date_add.
Find out how to get the current time in your DBMS (e.g. now(), getdate(), CURRENT_TIME)
Write a WHERE clause that returns rows where a time is between two other times. (Hint: BETWEEN is a keyword in SQL.) Start simple with something you know will always be true, like "2:00 is between 1:00 and 3:00".
Put these together, and you can build the query you wanted: select rows where the current time is between the startTime and the calculated end time.
For SQL Server I think:
select Id, Name, startTime, hours
from table
where
convert(time, getdate()) >= startTime
and convert(time, getdate()) < DATEADD(HH, hours, startTime)
if startTime column type is time.
EDIT
I strongly suggest to change the column to Time
If this cannot happen consider the solution below:
select convert( time, '6:00 am' )
-- result 06:00:00.0000000
select convert( time, '6:00 pm' )
-- result 18:00:00.0000000
So:
create view MyTableView as
select
Id,
Name,
StartTime = convert( time, startTime ),
EndTime = DATEADD(HH, hours, convert( time, startTime ) ),
ShiftDuration = hours
from
MyTable
UPDATE for 24h shift span
select
Id,
Name,
StartTime,
EndTime,
ShiftDuration
from
MyTableView
where
(
( StartTime < EndTime )
and ( convert(time, getdate()) >= StartTime )
and ( convert(time, getdate()) < EndTime )
)
or
(
( StartTime >= EndTime )
and ( convert(time, getdate()) >= StartTime )
and ( convert(time, getdate()) > EndTime )
)
You didn't specify your DBMS, so this is ANSI SQL:
select *
from (
select id, name, start_time, start_time + interval '1' hour * hours as end_Time
from shifts
) t
where current_time between start_time and end_time;
SQLFiddle example: http://sqlfiddle.com/#!15/f5428/1
I have two dates, From date and To Date.
Also i have two time fields, From Time and To Time.
The date field in the database is Datetime. I need to select data according to both date and time.
This is my query for selecting data between 13:00 to 15:00, but it is not suitable for 20:00 to 08:00.
where Date>= '2/01/2012' AND Date<'2/28/2013'
AND CAST(Date AS TIME) BETWEEN '20:00' AND '08:00'
Without seeing your specific error/unexpected results, I think the problem is that 20 is greater than 8.
You'll have to use two conditions:
where Date>= '2/01/2012' AND Date<'2/28/2013' AND (CAST(Date AS TIME) > '20:00' OR CAST(Date AS TIME) < '08:00')
EDIT: fixed condition
Is this what you are after?
WHERE Date BETWEEN '2012-01-01 20:00:00.000' AND '2012-12-01 08:00:00.000'
It is a little bit unclear whether you are attempting to generate the WHERE clause variables dynamically?
You need to combine your "date" and "time" parts together.
This code will illustrate how to do this:
SELECT the_date
, the_time
, DateAdd(hh, DatePart(hh, the_time), the_date) As hour_added
, DateAdd(mi, DatePart(mi, the_time), the_date) As minute_added
, DateAdd(mi, DatePart(mi, the_time), DateAdd(hh, DatePart(hh, the_time), the_date)) As both_added
FROM (
SELECT Cast('2013-02-28' As datetime) As the_date
, Cast('08:30' As datetime) As the_time
) As example
You can then use the resultant values in your comparison