SQL Server, how to find the time slot from a schedule table like I need to output first column's end time and next column's start time?
select
s, e,
Max(cid)as c_id,
ROW_NUMBER()OVER(order by CAST(s as datetime)) as row_id
from classroom
where Room like '3310' and Days like '%T%'
group by s,e
order by CAST(s as datetime)
For example:
s e c_id row_id
------- ------- ------- ------
9:30 10:45 235 1
11:00 12:15 236 2
12:30 13:45 238 3
14:00 15:15 1415 4
15:30 16:45 273 5
17:00 18:15 270 6
I need to output
10:45-11:00
12:15-12:30
13:45-14:00
Thanks
You can insert your data in a temp table and then query that temp table
select s,e,Max(cid)as c_id,
ROW_NUMBER()OVER(order by CAST(s as datetime))as row_id
into #t
from classroom
where Room like '3310' and Days like '%T%'
group by s,e
order by CAST(s as datetime)
select t1.e, t2.s
from #t t1
INNER JOIN #t t2 on t1.row_id + 1 = t2.row_id
If you want to know only when there's a time gap between one class finishing and the next starting add where t2.s > t1.e to Abhi's answer. If you need a minimum size of slot, say 15 minutes, use where DATEDIFF(mi, t1.e, t2.s) > 15.
Related
I have a table, such as:
TimeValue
Low
14:00
123
14:30
012
15:00
456
15:30
145
16:00
678
I want to return the minimum "Low" that occurs on or after each TimeValue, so expected results would be:
TimeValue
Min(Low)
14:00
012
14:30
012
15:00
145
15:30
145
16:00
678
Have tried:
SELECT
TimeValue AS thistime,
(SELECT
MIN(Low)
FROM MyTable
AND TimeValue >= thistime)
FROM MyTable
GROUP BY thistime
;
but obviously SQLite doesn't recognize thistime from the inner SELECT statement. How do we do this?
Instead of the MIN aggregation function, you can use the corresponding homonimous window function, which will return the minimum value for each row and for each partition. In order to group on the hour, you can use the STRFTIME function as follows:
SELECT TimeValue,
MIN(Low) OVER(PARTITION BY STRFTIME('%H', TimeValue))
FROM tab
Check the demo here.
I think I figured it out:
SELECT
a.TimeValue,
(SELECT MIN(Low) FROM MyTable WHERE TimeValue >= a.TimeValue) AS MyResult
FROM MyTable a;
I've done a search but I can't find any that are exactly what I need. I need to be able to calculate the amount of time that someone has been in the building over time in a sql query (T-SQL on SQL Server). The data looks like this:
UserId Clocking Status
------------------------------
1 01/12/2020 09:00 In
2 01/12/2020 09:12 In
1 01/12/2020 09:25 Out
3 01/12/2020 10:00 In
2 01/12/2020 10:45 Out
3 01/12/2020 13:11 Out
1 03/12/2020 11:14 In
2 03/12/2020 15:56 In
1 03/12/2020 16:04 Out
2 03/12/2020 17:00 Out
I want the output to look like this:
UserId TimeInBuilding
----------------------
1 03:35
2 05:25
3 03:11
Assuming that the ins/outs are perfectly interleaved, you can do this by assigning the next "out" time to the "in" time and aggregating:
select userid,
sum(datediff(second, clocking, out_time)) / (60.0 * 60) as decimal_hours
from (select t.*,
lead(clocking) over (partition by userid order by clocking) as out_time
from t
) t
where status = 'In'
group by userid;
You can convert this to HH:MM format using:
select userid,
convert(varchar(5),
convert(time,
dateadd(second,
sum(datediff(second, clocking, out_time),
0)
)
) as hhmm
from (select t.*,
lead(clocking) over (partition by userid order by clocking) as out_time
from t
) t
where status = 'In'
group by userid;
Here is a db<>fiddle.
I have a problem. I need to get the date difference in terms of hours in my table but the problem is it is saved in the same field. This is my table would look like.
RecNo. Employeeno recorddate recordtime recordval
1 001 8/22/2014 8:15 AM 1
2 001 8/22/2014 5:00 PM 2
3 001 8/24/2014 8:01 AM 1
4 001 8/24/2014 5:01 PM 2
1 indicates time in and 2 indicates time out. Now, How will i get the number of hours worked for each day? What i want to get is something like this.
Date hoursworked
8/22/2014 8
8/24/2014 8
I am using VS 2010 and SQL server 2005
You could self-join each "in" record with its corresponding "out" record and use datediff to subtract them:
SELECT time_in.employeeno AS "Employee No",
time_in.recorddate AS "Date",
DATEDIFF (hour, time_in.recordtime, time_out.recordtime)
AS "Hours Worked"
FROM (SELECT *
FROM my_table
WHERE recordval = 1) time_in
INNER JOIN (SELECT *
FROM my_table
WHERE recordval = 2) time_out
ON time_in.employeeno = time_out.employeeno AND
time_in.recorddate = time_out.recorddate
If you always record time in and time out for every employee, and just one per day, using a self-join should work:
SELECT
t1.Employeeno,
t1.recorddate,
t1.recordtime AS [TimeIn],
t2.recordtime AS [TimeOut],
DATEDIFF(HOUR,t1.recordtime, t2.recordtime) AS [HoursWorked]
FROM Table1 t1
INNER JOIN Table1 t2 ON
t1.Employeeno = t2.Employeeno
AND t1.recorddate = t2.recorddate
WHERE t1.recordval = 1 AND t2.recordval = 2
I included the recordtime fields as time in, time out, if you don't want them just remove them.
Note that this datediff calculation gives 9 hours, and not 8 as you suggested.
Sample SQL Fiddle
Using this sample data:
with table1 as (
select * from ( values
(1,'001', cast('20140822' as datetime),cast('08:15:00 am' as time),1)
,(2,'001', cast('20140822' as datetime),cast('05:00:00 pm' as time),2)
,(3,'001', cast('20140824' as datetime),cast('08:01:00 am' as time),1)
,(4,'001', cast('20140824' as datetime),cast('04:59:00 pm' as time),2)
,(5,'001', cast('20140825' as datetime),cast('10:01:00 pm' as time),1)
,(6,'001', cast('20140826' as datetime),cast('05:59:00 am' as time),2)
)data(RecNo,EmployeeNo,recordDate,recordTime,recordVal)
)
this query
SELECT
Employeeno
,convert(char(10),recorddate,120) as DateStart
,convert(char(5),cast(TimeIn as time)) as TimeIn
,convert(char(5),cast(TimeOut as time)) as TimeOut
,DATEDIFF(minute,timeIn, timeOut) / 60 AS [HoursWorked]
,DATEDIFF(minute,timeIn, timeOut) % 60 AS [MinutesWorked]
FROM (
SELECT
tIn.Employeeno,
tIn.recorddate,
dateadd(minute, datediff(minute,0,tIn.recordTime), tIn.recordDate)
as TimeIn,
( SELECT TOP 1
dateadd(minute, datediff(minute,0,tOut.recordTime), tOut.recordDate)
as TimeOut
FROM Table1 tOut
WHERE tOut.RecordVal = 2
AND tOut.EmployeeNo = tIn.EmployeeNo
AND tOut.RecNo > tIn.RecNo
ORDER BY tOut.EmployeeNo, tOut.RecNo
) as TimeOut
FROM Table1 tIn
WHERE tIn.recordval = 1
) T
yields (as desired)
Employeeno DateStart TimeIn TimeOut HoursWorked MinutesWorked
---------- ---------- ------ ------- ----------- -------------
001 2014-08-22 08:15 17:00 8 45
001 2014-08-24 08:01 16:59 8 58
001 2014-08-25 22:01 05:59 7 58
No assumptions are made about shifts not running across midnight (see case 3).
This particular implementation may not be the most performant way to construct this correlated subquery, so if there is a performance problem come back and we can look at it again. However running those tests requires a large dataset which I don't feel like constructing just now.
Im working on a SSRS / SQL project and trying to write a query to get the gaps between dates and I am completely lost with how to write this.Basically we have a number of devices which can be scheduled for use and I need a report to show when they are not in use.
I have a table with Device ID, EventStart and EventEnd times, I need to run a query to get the times between these events for each device but I am not really sure how to do this.
For example:
Device 1 Event A runs from `01/01/2012 08:00 - 01/01/2012 10:00`
Device 1 Event B runs from `01/01/2012 18:00 - 01/01/2012 20:00`
Device 1 Event C runs from `02/01/2012 18:00 - 02/01/2012 20:00`
Device 2 Event A runs from `01/01/2012 08:00 - 01/01/2012 10:00`
Device 2 Event B runs from `01/01/2012 18:00 - 01/01/2012 20:00`
My query should have as its result
`Device 1 01/01/2012 10:00 - 01/01/2012 18:00`
`Device 1 01/01/2012 20:00 - 02/01/2012 18:00`
`Device 2 01/01/2012 10:00 - 01/01/2012 18:00`
There will be around 4 - 5 devices on average in this table, and maybe 200 - 300 + events.
Updates:
Ok I'll update this to try give a bit more info since I dont seem to have explained this too well (sorry!)
What I am dealing with is a table which has details for Events, Each event is a booking of a flight simulator, We have a number of flight sims( refered to as devices in the table) and we are trying to generate a SSRS report which we can give to a customer to show the days / times each sim is available.
So I am going to pass in a start / end date parameter and select all availabilities between those dates. The results should then display as something like:
Device Available_From Available_To
1 01/01/2012 10:00 01/01/2012 18:00`
1 01/01/2012 20:00 02/01/2012 18:00`
2 01/01/2012 10:00 01/01/2012 18:00`
Also Events can sometimes overlap though this is very rare and due to bad data, it doesnt matter about an event on one device overlapping an event on a different device as I need to know availability for each device seperately.
The Query:
Assuming the fields containing the interval are named Start and Finish, and the table is named YOUR_TABLE, the query...
SELECT Finish, Start
FROM
(
SELECT DISTINCT Start, ROW_NUMBER() OVER (ORDER BY Start) RN
FROM YOUR_TABLE T1
WHERE
NOT EXISTS (
SELECT *
FROM YOUR_TABLE T2
WHERE T1.Start > T2.Start AND T1.Start < T2.Finish
)
) T1
JOIN (
SELECT DISTINCT Finish, ROW_NUMBER() OVER (ORDER BY Finish) RN
FROM YOUR_TABLE T1
WHERE
NOT EXISTS (
SELECT *
FROM YOUR_TABLE T2
WHERE T1.Finish > T2.Start AND T1.Finish < T2.Finish
)
) T2
ON T1.RN - 1 = T2.RN
WHERE
Finish < Start
...gives the following result on your test data:
Finish Start
2012-01-01 10:00:00.000 2012-01-01 18:00:00.000
The important property of this query is that it would work on overlapping intervals as well.
The Algorithm:
1. Merge Overlapping Intervals
The subquery T1 accepts only those interval starts that are outside other intervals. The subquery T2 does the same for interval ends. This is what removes overlaps.
The DISTINCT is important in case there are two identical interval starts (or ends) that are both outside other intervals. The WHERE Finish < Start simply eliminates any empty intervals (i.e. duration 0).
We also attach a row number relative to temporal ordering, which will be needed in the next step.
The T1 yields:
Start RN
2012-01-01 08:00:00.000 1
2012-01-01 18:00:00.000 2
The T2 yields:
Finish RN
2012-01-01 10:00:00.000 1
2012-01-01 20:00:00.000 2
2. Reconstruct the Result
We can now reconstruct either the "active" or the "inactive" intervals.
The inactive intervals are reconstructed by putting together end of the previous interval with the beginning of the next one, hence - 1 in the ON clause. Effectively, we put...
Finish RN
2012-01-01 10:00:00.000 1
...and...
Start RN
2012-01-01 18:00:00.000 2
...together, resulting in:
Finish Start
2012-01-01 10:00:00.000 2012-01-01 18:00:00.000
(The active intervals could be reconstructed by putting rows from T1 alongside rows from T2, by using JOIN ... ON T1.RN = T2.RN and reverting WHERE.)
The Example:
Here is a slightly more realistic example. The following test data:
Device Event Start Finish
Device 1 Event A 2012-01-01 08:00:00.000 2012-01-01 10:00:00.000
Device 2 Event B 2012-01-01 18:00:00.000 2012-01-01 20:00:00.000
Device 3 Event C 2012-01-02 11:00:00.000 2012-01-02 15:00:00.000
Device 4 Event D 2012-01-02 10:00:00.000 2012-01-02 12:00:00.000
Device 5 Event E 2012-01-02 10:00:00.000 2012-01-02 15:00:00.000
Device 6 Event F 2012-01-03 09:00:00.000 2012-01-03 10:00:00.000
Gives the following result:
Finish Start
2012-01-01 10:00:00.000 2012-01-01 18:00:00.000
2012-01-01 20:00:00.000 2012-01-02 10:00:00.000
2012-01-02 15:00:00.000 2012-01-03 09:00:00.000
First Answer -- but see below for final one with additional constraints added by OP.
--
If you want to get the next startTime after the most recent endTime and avoid overlaps, you want something like:
select
distinct
e1.deviceId,
e1.EventEnd,
e3.EventStart
from Events e1
join Events e3 on e1.eventEnd < e3.eventStart /* Finds the next start Time */
and e3.eventStart = (select min(eventStart) from Events e5
where e5.eventStart > e1.eventEnd)
and not exists (select * /* Eliminates an e1 rows if it is overlapped */
from Events e5
where e5.eventStart < e1.eventEnd
and e5.eventEnd > e1.eventEnd)
For the case of your three rows:
INSERT INTO Events VALUES (1, '01/01/2012 08:00', '01/01/2012 10:00')
INSERT INTO Events VALUES (2, '01/01/2012 18:00', '01/01/2012 20:00')
insert into Events values (2, '01/01/2012 09:00', '01/01/2012 11:00')
This gives 1 result:
January, 01 2012 11:00:00-0800 January, 01 2012 18:00:00-0800
However, I assume you probably want to match on DeviceId also. In which case, on the joins, you'd add e1.DeviceId = e3.DeviceId and e1.deviceId = e5.deviceId
SQL Fiddle here: http://sqlfiddle.com/#!3/3899c/8
--
OK, final edit. Here's a query adding in deviceIds and adding in a distinct to account for simultenously ending events:
SELECT distinct
e1.DeviceID,
e1.EventEnd as LastEndTime,
e3.EventStart as NextStartTime
FROM Events e1
join Events e3 on e1.eventEnd < e3.eventStart
and e3.deviceId = e1.deviceId
and e3.eventStart = (select min(eventStart) from Events e5
where e5.eventStart > e1.eventEnd
and e5.deviceId = e3.deviceId)
where not exists (select * from Events e7
where e7.eventStart < e1.eventEnd
and e7.eventEnd > e1.eventEnd
and e7.deviceId = e1.deviceId)
order by e1.deviceId, e1.eventEnd
The join to the e3 finds the next start. The join to e5 guarantees that this is the earliest starttime after the current endtime. The join to e7 eliminates a row if the end-time of the considered row is overlapped by a different row.
For this data:
INSERT INTO Events VALUES (1, '01/01/2012 08:00', '01/01/2012 10:00')
INSERT INTO Events VALUES (2, '01/01/2012 18:00', '01/01/2012 20:00')
insert into Events values (2, '01/01/2012 09:00', '01/01/2012 11:00')
insert into Events values (2, '01/02/2012 11:00', '01/02/2012 15:00')
insert into Events values (1, '01/02/2012 10:00', '01/02/2012 12:00')
insert into Events values (2, '01/02/2012 10:00', '01/02/2012 15:00')
insert into Events values (2, '01/03/2012 09:00', '01/03/2012 10:00')
You get this result:
1 January, 01 2012 10:00:00-0800 January, 02 2012 10:00:00-0800
2 January, 01 2012 11:00:00-0800 January, 01 2012 18:00:00-0800
2 January, 01 2012 20:00:00-0800 January, 02 2012 10:00:00-0800
2 January, 02 2012 15:00:00-0800 January, 03 2012 09:00:00-0800
SQL Fiddle here: http://sqlfiddle.com/#!3/db0fa/3
I'm going to assume that it's not really this simple... but here's a query based on my current understanding of your scenario:
DECLARE #Events TABLE (
DeviceID INT,
EventStart DATETIME,
EventEnd DATETIME
)
INSERT INTO #Events VALUES (1, '01/01/2012 08:00', '01/01/2012 10:00')
INSERT INTO #Events VALUES (2, '01/01/2012 18:00', '01/01/2012 20:00')
SELECT
e1.DeviceID,
e1.EventEnd,
e2.EventStart
FROM
#Events e1
JOIN #Events e2
ON e2.EventStart = (
SELECT MIN(EventStart)
FROM #Events
WHERE EventStart > e1.EventEnd
)
Does this solve your issue:
http://www.simple-talk.com/sql/t-sql-programming/find-missing-date-ranges-in-sql/
http://www.simple-talk.com/sql/t-sql-programming/missing-date-ranges--the-sequel/
The second one seems more relevant
'There is a table, where two of the columns are DateFrom and DateTo.
Both columns contain date and time values. How does one find the
missing date ranges or, in other words, all the date ranges that are
not covered by any of the entries in the table'.
Here is a Postgres solution that I just did, that does not involve stored procedures:
SELECT minute, sum(case when dp.id is null then 0 else 1 end) as s
FROM generate_series(
'2017-12-28'::timestamp,
'2017-12-30'::timestamp,
'1 minute'::interval
) minute
left outer join device_periods as dp
on minute >= dp.start_date and minute < dp.end_date
group by minute order by minute
The generate_series function generates a table that has one row for each minute in the date range. You can change the interval to 1 second, to be more precise. It is a postgres specific function, but probably something similar exists in other engines.
This query will give you all the minutes that are filled, and all that are blank. You can wrap this query in an outer query, that can group by hours, days or do some window function operations to get the exact output as you need it. For my purposes, I only needed to count if there are blanks or not.
I have a sql table of payroll data that has wage rates and effective dates associated with those wage rates, as well as hours worked on various dates. It looks somewhat like this:
EMPID DateWorked Hours WageRate EffectiveDate
1 1/1/2010 10 7.00 6/1/2009
1 1/1/2010 10 7.25 6/10/2009
1 1/1/2010 10 8.00 2/1/2010
1 1/10/2010 ...
2 1/1/2010 ...
...
And so on. Basically, the data has been combined in such a way that for every day worked, all of the employee's wage history is joined together, and I want to grab the wage rate associated with the LATEST effective date that is not later than the date worked. So in the example above, the rate of 7.25 that become effective on 6/10/2009 is what I want.
What kind of query can I put together for this? I can use MAX(EffectiveDate) alongwith a criteria based on being before the work date, but that only gives me the latest date itself, I want the associated wage. I am using Sql Server for this.
Alternatively, I have the original tables that were used to create this data. One of them contains the dates worked, and the hours as well as EMPID, the other contains the list of wage rates and effective dates. Is there a way to join these instead that would correctly apply the right wage rate for each work day?
I was thinking that I'd want to group by EMPID and then DateWorked, and do something from there. I want to get a result that gives me the wage rate that actually is the latest effective rate for each date worked
select p.*
from (
select EMPID, DateWorked, Max(EffectiveDate) as MaxEffectiveDate
from Payroll
where EffectiveDate <= DateWorked
group by EMPID, DateWorked
) pm
inner join Payroll p on pm.EMPID = p.EMPID and pm.DateWorked = p.DateWorked and pm.MaxEffectiveDate = p.EffectiveDate
Output:
EMPID DateWorked Hours WageRate EffectiveDate
----------- ----------------------- ----------- --------------------------------------- -----------------------
1 2010-01-01 00:00:00.000 10 7.25 2009-06-10 00:00:00.000
try this:
DECLARE #YourTable table (EMPID int, DateWorked datetime, Hours int
,WageRate numeric(6,2), EffectiveDate datetime)
INSERT INTO #YourTable VALUES (1,'1/1/2010' ,10, 7.00, '6/1/2009')
INSERT INTO #YourTable VALUES (1,'1/1/2010' ,10, 7.25, '6/10/2009')
INSERT INTO #YourTable VALUES (1,'1/1/2010' ,10, 8.00, '2/1/2010')
INSERT INTO #YourTable VALUES (1,'1/10/2010',10, 20.00,'12/1/2010')
INSERT INTO #YourTable VALUES (2,'1/1/2010' ,8 , 12.00, '2/1/2009')
SELECT
e.EMPID,e.WageRate,e.EffectiveDate
FROM #YourTable e
INNER JOIN (SELECT
EMPID,MAX(EffectiveDate) AS EffectiveDate
FROM #YourTable
WHERE EffectiveDate<GETDATE()+1
GROUP BY EMPID
) dt ON e.EMPID=dt.EMPID AND e.EffectiveDate=dt.EffectiveDate
ORDER BY e.EMPID
OUTPUT
EMPID WageRate EffectiveDate
----------- --------------------------------------- -----------------------
1 8.00 2010-02-01 00:00:00.000
2 12.00 2009-02-01 00:00:00.000
(2 row(s) affected)
Something like this ought to work:
SELECT T.* FROM T
INNER JOIN (
SELECT EMPID, MAX(EFFECTIVEDATE) EFFECTIVEDATE
FROM T
WHERE DATEWORKED <= EFFECTIVEDATE
GROUP BY EMPID) t2
ON T2.EMPID = T.EMPID
AND T2.EFFECTIVEDATE = T.EFFECTIVEDATE
SELECT TOP 1 EMPID, WageRate
FROM wages
WHERE ......
ORDER BY EffectiveDate DESC