Postgres - calculate total working hours based on IN and OUT entry - sql

I have the below tables:
1) My Company table
id | c_name | c_code | status
----+------------+----------+--------
1 | AAAAAAAAAA | AA1234 | Active
2) My User table
id | c_id | u_name | status | emp_id
----+------------+----------+--------+--------
1 | 1 | XXXXXXXX | Active | 1
2 | 1 | YYYYYYYY | Active | 2
3) My Attendance table
id | u_id | swipe_time | status
----+--------+------------------------+--------
1 | 1 | 2020-08-20 16:00:00 | IN
2 | 1 | 2020-08-20 20:00:00 | OUT
3 | 1 | 2020-08-20 21:00:00 | IN
4 | 1 | 2020-08-21 01:00:00 | OUT
5 | 1 | 2020-08-21 16:00:00 | IN
6 | 1 | 2020-08-21 19:00:00 | OUT
I need to calculate the attendance grouped by date, u_id like below:
Note: The query parameters would be the "From Date", "To Date" and "Company ID"
u_id | u_name | date | in_time | out_time | hrs
-----+-----------+-------------+----------------------+----------------------+-----
1 | XXXXXXXX | 2020-08-20 | 2020-08-20 16:00:00 | 2020-08-21 01:00:00 | 7
1 | XXXXXXXX | 2020-08-21 | 2020-08-21 16:00:00 | 2020-08-21 19:00:00 | 4
2 | YYYYYYYY | null | null | null | 0
Is this possible in PostgreSQL?

The tricky part is to expand one row that covers two (calendar) days to two rows and allocating the hours of the "next" day correctly.
The first part is to get a pivot table that combines IN/OUT pairs into a single row.
A simple (yet not very efficient) approach is:
select ain.u_id,
ain.swipe_time as time_in,
(select min(aout.swipe_time)
from attendance aout
where aout.u_id = ain.u_id
and aout.status = 'OUT'
and aout.swipe_time > ain.swipe_time) as time_out
from attendance ain
where ain.status = 'IN'
The next step is to break up the rows with more than one day into two rows.
This assumes that you never have an IN/OUT pair that covers more than two days!
with inout as (
select ain.u_id,
ain.swipe_time as time_in,
(select min(aout.swipe_time)
from attendance aout
where aout.u_id = ain.u_id
and aout.status = 'OUT'
and aout.swipe_time > ain.swipe_time) as time_out
from attendance ain
where ain.status = 'IN'
), expanded as (
select u_id,
time_in::date as "date",
time_in,
time_out
from inout
where time_in::date = time_out::date
union all
select i.u_id,
x.time_in::date as date,
x.time_in,
x.time_out
from inout i
cross join lateral (
select i.u_id,
i.time_in,
i.time_in::date + 1 as time_out
union all
select i.u_id,
i.time_out::date,
i.time_out
) x
where i.time_out::date > i.time_in::date
)
select *
from expanded;
The above returns the following for your sample data:
u_id | date | time_in | time_out
-----+------------+---------------------+--------------------
1 | 2020-08-20 | 2020-08-20 16:00:00 | 2020-08-20 20:00:00
1 | 2020-08-20 | 2020-08-20 21:00:00 | 2020-08-21 00:00:00
1 | 2020-08-21 | 2020-08-21 00:00:00 | 2020-08-21 01:00:00
1 | 2020-08-21 | 2020-08-21 16:00:00 | 2020-08-21 19:00:00
How does this work?
So we first select all those rows that start and end on the same day with this part:
select u_id,
time_in::date as "date",
time_in,
time_out
from inout
where time_in::date = time_out::date
The second part of the union splits up the rows that span two days by using a cross join that generates one row with the original start time and midnight, and another from midnight to the original end time:
select i.u_id,
x.time_in::date as date,
x.time_in,
x.time_out
from inout i
cross join lateral (
-- this generates a row for the first of the two days
select i.u_id,
i.time_in,
i.time_in::date + 1 as time_out
union all
-- this generates the row for the next day
select i.u_id,
i.time_out::date,
i.time_out
) x
where i.time_out::date > i.time_in::date
At the end the new "expanded" rows are then aggregated by grouping them by user and date and left joined to the users table to get the username as well.
with inout as (
select ain.u_id,
ain.swipe_time as time_in,
(select min(aout.swipe_time)
from attendance aout
where aout.u_id = ain.u_id
and aout.status = 'OUT'
and aout.swipe_time > ain.swipe_time) as time_out
from attendance ain
where ain.status = 'IN'
), expanded as (
select u_id,
time_in::date as "date",
time_in,
time_out
from inout
where time_in::date = time_out::date
union all
select i.u_id,
x.time_in::date as date,
x.time_in,
x.time_out
from inout i
cross join lateral (
select i.u_id,
i.time_in,
i.time_in::date + 1 as time_out
union all
select i.u_id,
i.time_out::date,
i.time_out
) x
where i.time_out::date > i.time_in::date
)
select u.id,
u.u_name,
e."date",
min(e.time_in) as time_in,
max(e.time_out) as time_out,
sum(e.time_out - e.time_in) as duration
from users u
left join expanded e on u.id = e.u_id
group by u.id, u.u_name, e."date"
order by u.id, e."date";
Which then results in:
u_id | date | time_in | time_out | duration
-----+------------+---------------------+---------------------+----------------------------------------------
1 | 2020-08-20 | 2020-08-20 16:00:00 | 2020-08-21 00:00:00 | 0 years 0 mons 0 days 7 hours 0 mins 0.0 secs
1 | 2020-08-21 | 2020-08-21 00:00:00 | 2020-08-21 19:00:00 | 0 years 0 mons 0 days 4 hours 0 mins 0.0 secs
The "duration" column is an interval which you can format to your liking.
Online example

Using lead window function makes it somewhat simpler and readable. For balanced IN and OUT attendance events this will work fine, otherwise there will be null values for the attendance hours. This makes sense, because either the person has not left yet or has not attended yet or attendance data is corrupt.
select
u.id u_id, u.u_name,
t.date_in date, t.t_in in_time, t.t_out out_time,
extract('hour' from t.t_out - t.t_in) hrs
from users u
left outer join
(
select u_id,
date_trunc('day', swipe_time) date_in,
swipe_time t_in,
lead(swipe_time, 1) over (partition by u_id order by u_id, swipe_time) t_out,
status
from attendance
) t
on u.id = t.u_id
where t.status = 'IN';

Related

Time difference between rows based on condition

Not really an expert with SQL and im having problems figuring out how to do this one.
Got a table like this one:
ID
Message
TimeStamp
User
1
Hello
2022-08-01 10:00:00
A
1
How are you?
2022-08-01 10:00:05
A
1
Hello there
2022-08-01 10:00:10
B
1
I am okay
2022-08-01 10:00:12
B
1
Good to know
2022-08-01 10:00:15
A
1
Bye
2022-08-01 10:00:25
B
2
Hello
2022-08-01 10:02:50
A
2
Hi
2022-08-01 10:03:50
B
I need to calculate the time difference each time there is a response from the B user after a message from A.
Expected result would be like this
ID
Difference
1
5
1
10
2
60
Trying to use Lead function to obtain the next desired timestamp but im not getting the expected result
Any tips or advice?
Thanks
Even if it is already answered - it's a nice use case for Vertica's MATCH() clause. Looking for a pattern consisting of sender = 'A' followed by sender = 'B'.
You get a pattern id, and then you can group by other stuff plus the pattern id to get max timestamp and min timestamp.
Also note that I renamed both "user" and "timestamp", as they are reserved words...
-- your input, don't use in final query
indata(ID,Message,ts,Usr) AS (
SELECT 1,'Hello' ,TIMESTAMP '2022-08-01 10:00:00','A'
UNION ALL SELECT 1,'How are you?',TIMESTAMP '2022-08-01 10:00:05','A'
UNION ALL SELECT 1,'Hello there' ,TIMESTAMP '2022-08-01 10:00:10','B'
UNION ALL SELECT 1,'I am okay' ,TIMESTAMP '2022-08-01 10:00:12','B'
UNION ALL SELECT 1,'Good to know',TIMESTAMP '2022-08-01 10:00:15','A'
UNION ALL SELECT 1,'Bye' ,TIMESTAMP '2022-08-01 10:00:25','B'
UNION ALL SELECT 2,'Hello' ,TIMESTAMP '2022-08-01 10:02:50','A'
UNION ALL SELECT 2,'Hi' ,TIMESTAMP '2022-08-01 10:03:50','B'
)
-- end of input, real query starts here , replace following comma with "WITH"
,
w_match_clause AS (
SELECT
*
, event_name()
, pattern_id()
, match_id()
FROM indata
MATCH (
PARTITION BY id ORDER BY ts
DEFINE
sentbya AS usr='A'
, sentbyb AS usr='B'
PATTERN
p AS (sentbya sentbyb)
)
-- ctl SELECT * FROM w_match_clause;
-- ctl ID | Message | ts | Usr | event_name | pattern_id | match_id
-- ctl ----+--------------+---------------------+-----+------------+------------+----------
-- ctl 1 | How are you? | 2022-08-01 10:00:05 | A | sentbya | 1 | 1
-- ctl 1 | Hello there | 2022-08-01 10:00:10 | B | sentbyb | 1 | 2
-- ctl 1 | Good to know | 2022-08-01 10:00:15 | A | sentbya | 2 | 1
-- ctl 1 | Bye | 2022-08-01 10:00:25 | B | sentbyb | 2 | 2
-- ctl 2 | Hello | 2022-08-01 10:02:50 | A | sentbya | 1 | 1
-- ctl 2 | Hi | 2022-08-01 10:03:50 | B | sentbyb | 1 | 2
)
SELECT
id
, MAX(ts) - MIN(ts) AS difference
FROM w_match_clause
GROUP BY
id
, pattern_id
ORDER BY
id;
-- out id | difference
-- out ----+------------
-- out 1 | 00:00:05
-- out 1 | 00:00:10
-- out 2 | 00:01
With mySQL 8.0:
WITH cte AS (
SELECT id, user, timestamp, ( LEAD(user) OVER (ORDER BY timestamp) ) AS to_user,
TIME_TO_SEC(TIMEDIFF(LEAD(timestamp) OVER (ORDER BY timestamp), timestamp)) AS time_diff
FROM msg_tab
)
SELECT id, time_diff
FROM cte
WHERE user='A' AND to_user IN ('B', NULL)

Oracle SQL - Get difference between dates based on check in and checkout records

Assume I have the following table data.
# | USER | Entrance | Transaction Date Time
-----------------------------------------------
1 | ALEX | INBOUND | 2020-01-01 10:20:00
2 | ALEX | OUTBOUND | 2020-01-02 10:00:00
3 | ALEX | INBOUND | 2020-01-04 11:30:00
4 | ALEX | OUTBOUND | 2020-01-07 15:00:00
5 | BEN | INBOUND | 2020-01-08 08:00:00
6 | BEN | OUTBOUND | 2020-01-09 09:00:00
I would like to know the total of how many days the user has stay outbound.
For each inbound and outbound is considered one trip, every trip exceeded 24 hours is considered as 2 days.
Below is my desired output:
No. of Days | Trips Count
----------------------------------
Stay < 1 day | 1
Stay 1 day | 1
Stay 2 days | 0
Stay 3 days | 0
Stay 4 days | 1
I would use lead() and aggregation. Assuming that the rows are properly interlaced:
select floor( (next_dt - dt) ) as num_days, count(*)
from (select t.*,
lead(dt) over (partition by user order by dt) as next_dt
from trips t
) t
where entrance = 'INBOUND'
group by floor( (next_dt - dt) )
order by num_days;
Note: This does not include the 0 rows. That does not seem central to your question and is a significant complication.
I still don't know what you mean with < 1 day, but this I got this far
Setup
create table trips (id number, name varchar2(10), entrance varchar2(10), ts TIMESTAMP);
insert into trips values( 1 , 'ALEX','INBOUND', TIMESTAMP '2020-01-01 10:20:00');
insert into trips values(2 , 'ALEX','OUTBOUND',TIMESTAMP '2020-01-02 10:00:00');
insert into trips values(3 , 'ALEX','INBOUND',TIMESTAMP '2020-01-04 11:30:00');
insert into trips values(4 , 'ALEX','OUTBOUND',TIMESTAMP '2020-01-07 15:00:00');
insert into trips values(5 , 'BEN','INBOUND',TIMESTAMP '2020-01-08 08:00:00');
insert into trips values(6 , 'BEN','OUTBOUND',TIMESTAMP '2020-01-09 07:00:00');
Query
select decode (t.days, 0 , 'Stay < 1 day', 1, 'Stay 1 day', 'Stay ' || t.days || ' days') Days , count(d.days) Trips_count
FROM (Select Rownum - 1 days From dual Connect By Rownum <= 6) t left join
(select extract (day from b.ts - a.ts) + 1 as days from trips a
inner join trips b on a.name = b.name
and a.entrance = 'INBOUND'
and b.entrance = 'OUTBOUND'
and a.ts < b.ts
and not exists (select ts from trips where entrance = 'OUTBOUND' and ts > a.ts and ts < b.ts)) d
on t.days = d.days
group by t.days order by t.days
Result
DAYS | TRIPS_COUNT
----------------|------------
Stay < 1 day | 0
Stay 1 day | 2
Stay 2 days | 0
Stay 3 days | 0
Stay 4 days | 1
Stay 5 days | 0
You could replace the 6 with a select max with the second subquery repeated

Counting intersecting time intervals in T-SQL

CODE:
CREATE TABLE #Temp1 (CoachID INT, BusyST DATETIME, BusyET DATETIME)
CREATE TABLE #Temp2 (CoachID INT, AvailableST DATETIME, AvailableET DATETIME)
INSERT INTO #Temp1 (CoachID, BusyST, BusyET)
SELECT 1,'2016-08-17 09:12:00','2016-08-17 10:11:00'
UNION
SELECT 3,'2016-08-17 09:30:00','2016-08-17 10:00:00'
UNION
SELECT 4,'2016-08-17 12:07:00','2016-08-17 13:10:00'
INSERT INTO #Temp2 (CoachID, AvailableST, AvailableET)
SELECT 1,'2016-08-17 09:07:00','2016-08-17 11:09:00'
UNION
SELECT 2,'2016-08-17 09:11:00','2016-08-17 09:30:00'
UNION
SELECT 3,'2016-08-17 09:24:00','2016-08-17 13:08:00'
UNION
SELECT 1,'2016-08-17 11:34:00','2016-08-17 12:27:00'
UNION
SELECT 4,'2016-08-17 09:34:00','2016-08-17 13:00:00'
UNION
SELECT 5,'2016-08-17 09:10:00','2016-08-17 09:55:00'
--RESULT-SET QUERY GOES HERE
DROP TABLE #Temp1
DROP TABLE #Temp2
DESIRED OUTPUT:
CoachID CanCoachST CanCoachET NumOfCoaches
1 2016-08-17 09:12:00.000 2016-08-17 09:24:00.000 2 --(ID2 = 2,5)
1 2016-08-17 09:24:00.000 2016-08-17 09:30:00.000 3 --(ID2 = 2,3,5)
1 2016-08-17 09:30:00.000 2016-08-17 09:34:00.000 1 --(ID2 = 5)
1 2016-08-17 09:34:00.000 2016-08-17 09:55:00.000 2 --(ID2 = 4,5)
1 2016-08-17 09:55:00.000 2016-08-17 10:00:00.000 1 --(ID2 = 4)
1 2016-08-17 10:00:00.000 2016-08-17 10:11:00.000 2 --(ID2 = 3,4)
3 2016-08-17 09:30:00.000 2016-08-17 09:34:00.000 1 --(ID2 = 5)
3 2016-08-17 09:34:00.000 2016-08-17 09:55:00.000 2 --(ID2 = 4,5)
3 2016-08-17 09:55:00.000 2016-08-17 10:00:00.000 1 --(ID2 = 4)
4 2016-08-17 12:07:00.000 2016-08-17 12:27:00.000 2 --(ID2 = 1,3)
4 2016-08-17 12:27:00.000 2016-08-17 13:08:00.000 1 --(ID2 = 3)
4 2016-08-17 13:08:00.000 2016-08-17 13:10:00.000 0 --(No one is available)
GOAL:
Consider #Temp1 as the table of team coaches (ID1) and their meeting times (ST1 = Meeting Start Time and ET1 = Meeting End Time).
Consider #Temp2 as the table of team coaches (ID2) and their total available times (ST2 = Available Start Time and ET2 = Available End Time).
Now, the goal is to find all possible coaches from #Temp2 who are available to coach during the meeting time of the coaches from #Temp1.
So for example, For the coach ID1 = 1, who is busy between 9:12 and 10:11 (data can span across multiple days, if that info matters), we have
coach ID2 = 2 and 5 that can coach between 9:12 and 9:24
, coach ID2 = 2,3, and 5 that can coach between 9:24 and 9:30
, coach ID2 = 5 that can coach between 9:30 and 9:34
, coach ID2 = 4 and 5 that can coach between 9:34 and 9:55
, coach ID2 = 4 that can coach between 9:55 and 10:00
, and coach ID2 = 3 and 4 that can coach between 10:00 and 10:11 (note how ID 3, although available in #Temp2 table between 9:24 and 13:08, it can't coach for ID1 = 1 between 9:24 and 10:00 because its also busy between 9:30 and 10:00.
My effort so far: Only dealing with breaking #Temp1's time bracket so far. Still need to figure out A) how to remove that non-busy time window from the output B) add a field/map it to right T1's CoachIDs.
;WITH ED
AS (SELECT BusyET, CoachID FROM #Temp1
UNION ALL
SELECT BusyST, CoachID FROM #Temp1
)
,Brackets
AS (SELECT MIN(BusyST) AS BusyST
,( SELECT MIN(BusyET)
FROM ED e
WHERE e.BusyET > MIN(BusyST)
) AS BusyET
FROM #Temp1 T
UNION ALL
SELECT B.BusyET
,e.BusyET
FROM Brackets B
INNER JOIN ED E ON B.BusyET < E.BusyET
WHERE NOT EXISTS (
SELECT *
FROM ED E2
WHERE E2.BusyET > B.BusyET
AND E2.BusyET < E.BusyET
)
)
SELECT *
FROM Brackets
ORDER BY BusyST;
I think I need to join on comparing ST/ET dates between two tables where IDs don't match each other. But I'm having trouble figuring out how to actually get only the meeting time window and unique count.
Updated with better schema/data-set. Also note, even though CoachID 4 is not "scheduled" to be available, he's still listed as busy for that last few minutes. And there can be scenario where no one else is available to work during that time, in which case, we can return 0 cnt record (or not return it if it's really complicated).
Again, the goal is to find count and combination of all available CoachIDs and their Available time window that can coach for the CoachIDs listed in the busy table.
Updated with more sample description matching sample data.
The query in this answer was inspired by the Packing Intervals by Itzik Ben-Gan.
At first I didn't understand the full complexity of the requirements and assumed that intervals in Table1 and Table2 don't overlap. I assumed that the same coach can't be busy and available at the same time.
It turns out that my assumption was wrong, so the first variant of the query that I'm leaving below has to be extended with preliminary step that subtracts all intervals stored in Table1 from intervals stored in Table2.
It uses the similar idea. Each start of the "available" interval is marked with +1 EventType and end of the "available" interval is marked with -1 EventType. For "busy" intervals the marks are reversed. "Busy" interval starts with -1 and ends with +1. This is done in C1_Subtract.
Then running total tells us where the "truly" available intervals are (C2_Subtract). Finally, CTE_Available leaves only "truly" available intervals.
Sample data
I added few rows to illustrate what happens if no coaches are available. I also added CoachID=9, which is not in the initial results of the first variant of the query.
CREATE TABLE #Temp1 (CoachID INT, BusyST DATETIME, BusyET DATETIME);
CREATE TABLE #Temp2 (CoachID INT, AvailableST DATETIME, AvailableET DATETIME);
-- Start time is inclusive
-- End time is exclusive
INSERT INTO #Temp1 (CoachID, BusyST, BusyET) VALUES
(1, '2016-08-17 09:12:00','2016-08-17 10:11:00'),
(3, '2016-08-17 09:30:00','2016-08-17 10:00:00'),
(4, '2016-08-17 12:07:00','2016-08-17 13:10:00'),
(6, '2016-08-17 15:00:00','2016-08-17 16:00:00'),
(9, '2016-08-17 15:00:00','2016-08-17 16:00:00');
INSERT INTO #Temp2 (CoachID, AvailableST, AvailableET) VALUES
(1,'2016-08-17 09:07:00','2016-08-17 11:09:00'),
(2,'2016-08-17 09:11:00','2016-08-17 09:30:00'),
(3,'2016-08-17 09:24:00','2016-08-17 13:08:00'),
(1,'2016-08-17 11:34:00','2016-08-17 12:27:00'),
(4,'2016-08-17 09:34:00','2016-08-17 13:00:00'),
(5,'2016-08-17 09:10:00','2016-08-17 09:55:00'),
(7,'2016-08-17 15:10:00','2016-08-17 15:20:00'),
(8,'2016-08-17 15:15:00','2016-08-17 15:25:00'),
(7,'2016-08-17 15:40:00','2016-08-17 15:55:00'),
(9,'2016-08-17 15:05:00','2016-08-17 15:07:00'),
(9,'2016-08-17 15:40:00','2016-08-17 16:55:00');
Intermediate results of CTE_Available
+---------+-------------------------+-------------------------+
| CoachID | AvailableST | AvailableET |
+---------+-------------------------+-------------------------+
| 1 | 2016-08-17 09:07:00.000 | 2016-08-17 09:12:00.000 |
| 1 | 2016-08-17 10:11:00.000 | 2016-08-17 11:09:00.000 |
| 1 | 2016-08-17 11:34:00.000 | 2016-08-17 12:27:00.000 |
| 2 | 2016-08-17 09:11:00.000 | 2016-08-17 09:30:00.000 |
| 3 | 2016-08-17 09:24:00.000 | 2016-08-17 09:30:00.000 |
| 3 | 2016-08-17 10:00:00.000 | 2016-08-17 13:08:00.000 |
| 4 | 2016-08-17 09:34:00.000 | 2016-08-17 12:07:00.000 |
| 5 | 2016-08-17 09:10:00.000 | 2016-08-17 09:55:00.000 |
| 7 | 2016-08-17 15:10:00.000 | 2016-08-17 15:20:00.000 |
| 7 | 2016-08-17 15:40:00.000 | 2016-08-17 15:55:00.000 |
| 8 | 2016-08-17 15:15:00.000 | 2016-08-17 15:25:00.000 |
| 9 | 2016-08-17 16:00:00.000 | 2016-08-17 16:55:00.000 |
+---------+-------------------------+-------------------------+
Now we can use these intermediate results of CTE_Available instead of #Temp2 in the first variant of the query. See detailed explanations below the first variant of the query.
Full query
WITH
C1_Subtract
AS
(
SELECT
CoachID
,AvailableST AS ts
,+1 AS EventType
FROM #Temp2
UNION ALL
SELECT
CoachID
,AvailableET AS ts
,-1 AS EventType
FROM #Temp2
UNION ALL
SELECT
CoachID
,BusyST AS ts
,-1 AS EventType
FROM #Temp1
UNION ALL
SELECT
CoachID
,BusyET AS ts
,+1 AS EventType
FROM #Temp1
)
,C2_Subtract AS
(
SELECT
C1_Subtract.*
,SUM(EventType)
OVER (
PARTITION BY CoachID
ORDER BY ts, EventType DESC
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
AS cnt
,LEAD(ts)
OVER (
PARTITION BY CoachID
ORDER BY ts, EventType DESC)
AS NextTS
FROM C1_Subtract
)
,CTE_Available
AS
(
SELECT
C2_Subtract.CoachID
,C2_Subtract.ts AS AvailableST
,C2_Subtract.NextTS AS AvailableET
FROM C2_Subtract
WHERE cnt > 0
)
,CTE_Intervals
AS
(
SELECT
TBusy.CoachID AS BusyCoachID
,TBusy.BusyST
,TBusy.BusyET
,CA.CoachID AS AvailableCoachID
,CA.AvailableST
,CA.AvailableET
-- max of start time
,CASE WHEN CA.AvailableST < TBusy.BusyST
THEN TBusy.BusyST
ELSE CA.AvailableST
END AS ST
-- min of end time
,CASE WHEN CA.AvailableET > TBusy.BusyET
THEN TBusy.BusyET
ELSE CA.AvailableET
END AS ET
FROM
#Temp1 AS TBusy
CROSS APPLY
(
SELECT
TAvailable.*
FROM
CTE_Available AS TAvailable
WHERE
-- the same coach can't be available and busy
TAvailable.CoachID <> TBusy.CoachID
-- intervals intersect
AND TAvailable.AvailableST < TBusy.BusyET
AND TAvailable.AvailableET > TBusy.BusyST
) AS CA
)
,C1 AS
(
SELECT
BusyCoachID
,AvailableCoachID
,ST AS ts
,+1 AS EventType
FROM CTE_Intervals
UNION ALL
SELECT
BusyCoachID
,AvailableCoachID
,ET AS ts
,-1 AS EventType
FROM CTE_Intervals
UNION ALL
SELECT
CoachID AS BusyCoachID
,CoachID AS AvailableCoachID
,BusyST AS ts
,+1 AS EventType
FROM #Temp1
UNION ALL
SELECT
CoachID AS BusyCoachID
,CoachID AS AvailableCoachID
,BusyET AS ts
,-1 AS EventType
FROM #Temp1
)
,C2 AS
(
SELECT
C1.*
,SUM(EventType)
OVER (
PARTITION BY BusyCoachID
ORDER BY ts, EventType DESC, AvailableCoachID
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
- 1 AS cnt
,LEAD(ts)
OVER (
PARTITION BY BusyCoachID
ORDER BY ts, EventType DESC, AvailableCoachID)
AS NextTS
FROM C1
)
SELECT
BusyCoachID AS CoachID
,ts AS CanCoachST
,NextTS AS CanCoachET
,cnt AS NumOfCoaches
FROM C2
WHERE ts <> NextTS
ORDER BY BusyCoachID, CanCoachST
;
Final result
+---------+-------------------------+-------------------------+--------------+
| CoachID | CanCoachST | CanCoachET | NumOfCoaches |
+---------+-------------------------+-------------------------+--------------+
| 1 | 2016-08-17 09:12:00.000 | 2016-08-17 09:24:00.000 | 2 |
| 1 | 2016-08-17 09:24:00.000 | 2016-08-17 09:30:00.000 | 3 |
| 1 | 2016-08-17 09:30:00.000 | 2016-08-17 09:34:00.000 | 1 |
| 1 | 2016-08-17 09:34:00.000 | 2016-08-17 09:55:00.000 | 2 |
| 1 | 2016-08-17 09:55:00.000 | 2016-08-17 10:00:00.000 | 1 |
| 1 | 2016-08-17 10:00:00.000 | 2016-08-17 10:11:00.000 | 2 |
| 3 | 2016-08-17 09:30:00.000 | 2016-08-17 09:34:00.000 | 1 |
| 3 | 2016-08-17 09:34:00.000 | 2016-08-17 09:55:00.000 | 2 |
| 3 | 2016-08-17 09:55:00.000 | 2016-08-17 10:00:00.000 | 1 |
| 4 | 2016-08-17 12:07:00.000 | 2016-08-17 12:27:00.000 | 2 |
| 4 | 2016-08-17 12:27:00.000 | 2016-08-17 13:08:00.000 | 1 |
| 4 | 2016-08-17 13:08:00.000 | 2016-08-17 13:10:00.000 | 0 |
| 6 | 2016-08-17 15:00:00.000 | 2016-08-17 15:10:00.000 | 0 |
| 6 | 2016-08-17 15:10:00.000 | 2016-08-17 15:15:00.000 | 1 |
| 6 | 2016-08-17 15:15:00.000 | 2016-08-17 15:20:00.000 | 2 |
| 6 | 2016-08-17 15:20:00.000 | 2016-08-17 15:25:00.000 | 1 |
| 6 | 2016-08-17 15:25:00.000 | 2016-08-17 15:40:00.000 | 0 |
| 6 | 2016-08-17 15:40:00.000 | 2016-08-17 15:55:00.000 | 1 |
| 6 | 2016-08-17 15:55:00.000 | 2016-08-17 16:00:00.000 | 0 |
| 9 | 2016-08-17 15:00:00.000 | 2016-08-17 15:10:00.000 | 0 |
| 9 | 2016-08-17 15:10:00.000 | 2016-08-17 15:15:00.000 | 1 |
| 9 | 2016-08-17 15:15:00.000 | 2016-08-17 15:20:00.000 | 2 |
| 9 | 2016-08-17 15:20:00.000 | 2016-08-17 15:25:00.000 | 1 |
| 9 | 2016-08-17 15:25:00.000 | 2016-08-17 15:40:00.000 | 0 |
| 9 | 2016-08-17 15:40:00.000 | 2016-08-17 15:55:00.000 | 1 |
| 9 | 2016-08-17 15:55:00.000 | 2016-08-17 16:00:00.000 | 0 |
+---------+-------------------------+-------------------------+--------------+
I'd recommend to create the following indexes to avoid some Sorts in the execution plan.
CREATE UNIQUE NONCLUSTERED INDEX [IX_CoachID_BusyST] ON #Temp1
(
CoachID ASC,
BusyST ASC
);
CREATE UNIQUE NONCLUSTERED INDEX [IX_CoachID_BusyET] ON #Temp1
(
CoachID ASC,
BusyET ASC
);
CREATE UNIQUE NONCLUSTERED INDEX [IX_CoachID_AvailableST] ON #Temp2
(
CoachID ASC,
AvailableST ASC
);
CREATE UNIQUE NONCLUSTERED INDEX [IX_CoachID_AvailableET] ON #Temp2
(
CoachID ASC,
AvailableET ASC
);
On real data, though, the bottleneck may be somewhere else, which may depend on the data distribution. The query is rather complicated and tuning it without real data would be too much guesswork.
First variant of the query
Run the query step-by-step, CTE-by-CTE and examine intermediate results to undestand how it works.
CTE_Intervals gives us a list of available intervals that intersect with busy intervals.
C1 puts both start and end times in the same column with the corresponding EventType. This will help us track when an interval starts or ends.
A running total of EventType gives the count of available coaches. C1 unions busy coaches into the mix to properly count cases when no coach is available.
WITH
CTE_Intervals
AS
(
SELECT
TBusy.CoachID AS BusyCoachID
,TBusy.BusyST
,TBusy.BusyET
,CA.CoachID AS AvailableCoachID
,CA.AvailableST
,CA.AvailableET
-- max of start time
,CASE WHEN CA.AvailableST < TBusy.BusyST
THEN TBusy.BusyST
ELSE CA.AvailableST
END AS ST
-- min of end time
,CASE WHEN CA.AvailableET > TBusy.BusyET
THEN TBusy.BusyET
ELSE CA.AvailableET
END AS ET
FROM
#Temp1 AS TBusy
CROSS APPLY
(
SELECT
TAvailable.*
FROM
#Temp2 AS TAvailable
WHERE
-- the same coach can't be available and busy
TAvailable.CoachID <> TBusy.CoachID
-- intervals intersect
AND TAvailable.AvailableST < TBusy.BusyET
AND TAvailable.AvailableET > TBusy.BusyST
) AS CA
)
,C1 AS
(
SELECT
BusyCoachID
,AvailableCoachID
,ST AS ts
,+1 AS EventType
FROM CTE_Intervals
UNION ALL
SELECT
BusyCoachID
,AvailableCoachID
,ET AS ts
,-1 AS EventType
FROM CTE_Intervals
UNION ALL
SELECT
CoachID AS BusyCoachID
,CoachID AS AvailableCoachID
,BusyST AS ts
,+1 AS EventType
FROM #Temp1
UNION ALL
SELECT
CoachID AS BusyCoachID
,CoachID AS AvailableCoachID
,BusyET AS ts
,-1 AS EventType
FROM #Temp1
)
,C2 AS
(
SELECT
C1.*
,SUM(EventType)
OVER (
PARTITION BY BusyCoachID
ORDER BY ts, EventType DESC, AvailableCoachID
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
- 1 AS cnt
,LEAD(ts)
OVER (
PARTITION BY BusyCoachID
ORDER BY ts, EventType DESC, AvailableCoachID)
AS NextTS
FROM C1
)
SELECT
BusyCoachID AS CoachID
,ts AS CanCoachST
,NextTS AS CanCoachET
,cnt AS NumOfCoaches
FROM C2
WHERE ts <> NextTS
ORDER BY BusyCoachID, CanCoachST
;
DROP TABLE #Temp1;
DROP TABLE #Temp2;
Result
I've added comments for each line with IDs of available coaches that were counted.
Now I understand why my initial result was not the same as your expected result.
+---------+---------------------+---------------------+--------------+
| CoachID | CanCoachST | CanCoachET | NumOfCoaches |
+---------+---------------------+---------------------+--------------+
| 1 | 2016-08-17 09:12:00 | 2016-08-17 09:24:00 | 2 | 2,5
| 1 | 2016-08-17 09:24:00 | 2016-08-17 09:30:00 | 3 | 2,3,5
| 1 | 2016-08-17 09:30:00 | 2016-08-17 09:34:00 | 2 | 3,5
| 1 | 2016-08-17 09:34:00 | 2016-08-17 09:55:00 | 3 | 3,4,5
| 1 | 2016-08-17 09:55:00 | 2016-08-17 10:11:00 | 2 | 3,4
| 3 | 2016-08-17 09:30:00 | 2016-08-17 09:34:00 | 2 | 1,5
| 3 | 2016-08-17 09:34:00 | 2016-08-17 09:55:00 | 3 | 1,4,5
| 3 | 2016-08-17 09:55:00 | 2016-08-17 10:00:00 | 2 | 1,4
| 4 | 2016-08-17 12:07:00 | 2016-08-17 12:27:00 | 2 | 3,1
| 4 | 2016-08-17 12:27:00 | 2016-08-17 13:08:00 | 1 | 3
| 4 | 2016-08-17 13:08:00 | 2016-08-17 13:10:00 | 0 | none
| 6 | 2016-08-17 15:00:00 | 2016-08-17 15:10:00 | 0 | none
| 6 | 2016-08-17 15:10:00 | 2016-08-17 15:15:00 | 1 | 7
| 6 | 2016-08-17 15:15:00 | 2016-08-17 15:20:00 | 2 | 7,8
| 6 | 2016-08-17 15:20:00 | 2016-08-17 15:25:00 | 1 | 8
| 6 | 2016-08-17 15:25:00 | 2016-08-17 15:40:00 | 0 | none
| 6 | 2016-08-17 15:40:00 | 2016-08-17 15:55:00 | 1 | 7
| 6 | 2016-08-17 15:55:00 | 2016-08-17 16:00:00 | 0 | none
+---------+---------------------+---------------------+--------------+
This query will do the calculations:
SELECT TT1.ID1
, case when TT2.ST2 < TT1.ST1 THEN TT1.ST1 ELSE TT2.ST2 END
, case when TT2.ET2 > TT1.ET1 THEN TT1.ET1 ELSE TT2.ET2 END
, COUNT(distinct TT2.id2)
FROM #Temp1 TT1 INNER JOIN #Temp2 TT2
ON TT1.ET1 > TT2.ST2 AND TT1.ST1 < TT2.ET2 AND TT1.ID1 <> TT2.ID2
GROUP BY TT1.ID1
, case when TT2.ST2 < TT1.ST1 THEN TT1.ST1 ELSE TT2.ST2 END
, case when TT2.ET2 > TT1.ET1 THEN TT1.ET1 ELSE TT2.ET2 END
However, the result will include the slots where coaches cal fill in for the full time slot, e.g for the Coach 1 there will be three slots: from 9:00 to 9:30 with substitute coach #2, from 9:30 to 10:00 substitute coach #4 and the timeslot from 9:00 to 10:00 with substitute coaches #3 and #4. Here is the whole result:
ID1
----------- ----------------------- ----------------------- -----------
1 2016-08-17 09:00:00.000 2016-08-17 09:30:00.000 1
1 2016-08-17 09:00:00.000 2016-08-17 10:00:00.000 2
1 2016-08-17 09:30:00.000 2016-08-17 10:00:00.000 1
3 2016-08-17 09:30:00.000 2016-08-17 10:00:00.000 3
4 2016-08-17 12:00:00.000 2016-08-17 12:30:00.000 1
4 2016-08-17 12:00:00.000 2016-08-17 13:00:00.000 1
As best I can tell, what you're looking for is something like this:
;WITH CTE AS (
SELECT ID1, ST1, DATEADD(MINUTE, 30, ST1) ET1
FROM #Temp1
UNION ALL
SELECT C.ID1, C.ET1, DATEADD(MINUTE, 30, C.ET1)
FROM CTE C
JOIN #Temp1 T ON T.ID1 = C.ID1
WHERE T.ET1 >= DATEADD(MINUTE, 30, C.ET1))
SELECT *
FROM CTE C
OUTER APPLY (
SELECT COUNT(*) ID2Cnt
FROM #Temp2 T
WHERE ST2 <= C.ST1
AND ET2 >= C.ET1
AND ID2 <> C.ID1
AND NOT EXISTS (
SELECT 1
FROM CTE
WHERE ID1 = T.ID2
AND ST1 <= C.ST1
AND ET1 >= C.ET1)) T
ORDER BY ID1, ST1;
The CTE will split your #Temp1 coaches up into half hour slots, and then I'm assuming you want to find all the people in #Temp2 who aren't the same ID and have a shift that starts earlier or at the same time and ends after or at the same time... NOTE: I'm assuming blocks can only be half an hour here.
EDIT: Never mind... I just realised you also want to discount the busy people in #Temp1 from the result set so I added a not exists clause in the apply...
I recommend using the concept of an interval / timeslot table.
Another way of explaining it is consider a "Time Dimension Table"
Define all your times, and then record your facts with references to the time intervals at the granularity you care about. Because you had times ending in 7 and 11 minutes I chose 1 minute intervals, though I recommend 15-30 minute intervals.
By doing this it makes it easy to join / compare the tables.
Consider design / implementation below:
-- dimension table
-- drop table #intervals
create table #intervals(intervalId int identity(1,1) not null primary key clustered,intervalStartTime datetime unique)
declare #s datetime, #e datetime, #i int
set #s = '2016-08-16'
set #e = '2016-08-18'
set #i = 1
while (#s <= #e )
begin
insert into #intervals(intervalStartTime) values(#s)
set #s = dateadd(minute, #i, #s)
end
-- fact table:
-- drop table #Fact
create table #Fact(intervalId int, coachid int, isBusy int default(0) , isAvailable int default(0))
-- record every coach's times
insert into #Fact(coachid,intervalId)
select distinct c.coachid, i.intervalId
from
(
select distinct coachid from #temp1
union
select distinct coachid from #temp2
) c cross join #intervals i
-- record free / busy info
update f set isbusy = 1
from #intervals i inner join #fact f on i.intervalId = f.intervalId
inner join #temp1 t on f.coachid = t.coachid and i.intervalStartTime between t.BusyST and t.BusyET
-- record free / busy info
update f set isAvailable = 1
from #intervals i inner join #fact f on i.intervalId = f.intervalId
inner join #temp2 t on f.coachid = t.coachid and i.intervalStartTime between t.AvailableST and t.AvailableET
-- construct your query to find common times,etc
select * from #intervals i inner join #Fact f on i.intervalId = f.intervalId
-- example result showing # of coaches available vs free
select i.intervalId, i.intervalStartTime, sum(isBusy) as coachesBusy, sum(isAvailable) as coachesAvailable
from #intervals i inner join #Fact f on i.intervalId = f.intervalId
group by i.intervalId, i.intervalStartTime
having sum(isBusy) < sum(isAvailable)
you can then look for common or unique interval ids however you need.
let me know if you require additional clarification.
I'm using a little numbers table ... you don't need something for dates, just numbers. What I am building here is smaller than what you would use in a real scenario.
CREATE TABLE dbo.Numbers (Num INT PRIMARY KEY CLUSTERED);
WITH E1 AS (SELECT N FROM (VALUES (1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) AS t(N))
,E2 AS (SELECT N = 1 FROM E1 AS a, E1 AS b)
,E4 AS (SELECT N = 1 FROM E2 AS a, E2 AS b)
,cteTally AS (SELECT N = 0 UNION ALL
SELECT N = ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E4)
INSERT INTO dbo.Numbers (Num)
SELECT N FROM cteTally;
Pleae note the #startDate below ... it is artificially close to the dates you're dealing with and in a real prod scenario you would have that date be earlier to go along with your larger Numbers table.
Here is the solution to your problem and it will work with older SQL Server versions (as well as the 2012 you have tagged):
DECLARE #startDate DATETIME = '20160817';
WITH cteBusy AS
(
SELECT num.Num
, busy.CoachID
FROM #Temp1 AS busy
JOIN dbo.Numbers AS num
ON num.Num >= DATEDIFF(MINUTE, #startDate, busy.BusyST)
AND num.Num < DATEDIFF(MINUTE, #startDate, busy.BusyET)
)
, cteAvailable AS
(
SELECT num.Num
, avail.CoachID
FROM #Temp2 AS avail
JOIN dbo.Numbers AS num
ON num.Num >= DATEDIFF(MINUTE, #startDate, avail.AvailableST)
AND num.Num < DATEDIFF(MINUTE, #startDate, avail.AvailableET)
LEFT JOIN cteBusy AS b
ON b.Num = num.Num
AND b.CoachID = avail.CoachID
WHERE b.Num IS NULL
)
, cteGrouping AS
(
SELECT b.Num
, b.CoachID
, NumOfCoaches = COUNT(a.CoachID)
FROM cteBusy AS b
LEFT JOIN cteAvailable AS a
ON a.Num = b.Num
GROUP BY b.Num, b.CoachID
)
, cteFinal AS
(
SELECT cte.Num
, cte.CoachID
, cte.NumOfCoaches
, block = cte.Num - ROW_NUMBER() OVER(PARTITION BY cte.CoachID, cte.NumOfCoaches ORDER BY cte.Num)
FROM cteGrouping AS cte
)
SELECT cte.CoachID
, CanCoachST = DATEADD(MINUTE, MIN(cte.Num), #startDate)
, CanCoachET = DATEADD(MINUTE, MAX(cte.Num) + 1, #startDate)
, cte.NumOfCoaches
FROM cteFinal AS cte
GROUP BY cte.CoachId, cte.NumOfCoaches, cte.block
ORDER BY cte.CoachID, CanCoachST;
Enjoy!
I believe the following query will work, however I can make no promises on performance.
CREATE TABLE #Temp1 (CoachID INT, BusyST DATETIME, BusyET DATETIME)
CREATE TABLE #Temp2 (CoachID INT, AvailableST DATETIME, AvailableET DATETIME)
INSERT INTO #Temp1 (CoachID, BusyST, BusyET)
SELECT 1,'2016-08-17 09:12:00','2016-08-17 10:11:00'
UNION
SELECT 3,'2016-08-17 09:30:00','2016-08-17 10:00:00'
UNION
SELECT 4,'2016-08-17 12:07:00','2016-08-17 13:10:00'
INSERT INTO #Temp2 (CoachID, AvailableST, AvailableET)
SELECT 1,'2016-08-17 09:07:00','2016-08-17 11:09:00'
UNION
SELECT 2,'2016-08-17 09:11:00','2016-08-17 09:30:00'
UNION
SELECT 3,'2016-08-17 09:24:00','2016-08-17 13:08:00'
UNION
SELECT 1,'2016-08-17 11:34:00','2016-08-17 12:27:00'
UNION
SELECT 4,'2016-08-17 09:34:00','2016-08-17 13:00:00'
UNION
SELECT 5,'2016-08-17 09:10:00','2016-08-17 09:55:00'
;WITH WorkScheduleWithID -- Select work schedule (#Temp2 – available times) and generate ID for each schedule entry.
AS
(
SELECT ROW_NUMBER() OVER (ORDER BY [CoachID]) AS [ID]
,[WS].[CoachID]
,[WS].[AvailableST] AS [Start]
,[WS].[AvailableET] As [End]
FROM #Temp2 [WS]
), SchedulesIntersect -- Determine where work schedule and meeting schedule (busy times) intersect.
AS
(
SELECT [ID]
,[CoachID]
,[Start]
,[End]
,[IntersectTime]
,SUM([Availability]) OVER (PARTITION BY [ID] ORDER BY [IntersectTime]) AS GroupID
FROM (
SELECT [WS].[ID]
,[WS].[CoachID]
,[WS].[Start]
,[WS].[End]
,[MS1].[BusyST] AS [IntersectTime]
,0 AS [Availability]
FROM WorkScheduleWithID [WS]
INNER JOIN #Temp1 [MS1] ON ([MS1].[CoachID] = [WS].[CoachID])
AND
( ([MS1].[BusyST] > [WS].[Start]) AND ([MS1].[BusyST] < [WS].[End]) ) -- Meeting start contained with in work schedule
UNION ALL
SELECT [WS].[ID]
,[WS].[CoachID]
,[WS].[Start]
,[WS].[End]
,[MS2].[BusyET] AS [IntersectTime]
,1 AS [Availability]
FROM WorkScheduleWithID [WS]
INNER JOIN #Temp1 [MS2] ON ([MS2].[CoachID] = [WS].[CoachID])
AND
( ([MS2].BusyET > [WS].[Start]) AND ([MS2].BusyET < [WS].[End]) ) -- Meeting end contained with in work schedule
) Intersects
),ActualAvailability -- Determine actual availability of each coach based on work schedule and busy time.
AS
(
SELECT [ID]
,[CoachID]
,(
CASE
WHEN [GroupID] = 0 THEN [Start]
ELSE MIN([IntersectTime])
END
) AS [Start]
,(
CASE
WHEN ( ([GroupID] > 0) AND (MIN([IntersectTime]) = MAX([IntersectTime])) ) THEN [End]
ELSE MAX([IntersectTime])
END
) AS [End]
FROM SchedulesIntersect
GROUP BY [ID], [CoachID], [Start], [End], [GroupID]
UNION ALL
SELECT [ID]
,[CoachID]
,[Start]
,[End]
FROM WorkScheduleWithID WS
WHERE WS.ID NOT IN (SELECT ID FROM SchedulesIntersect)
),TimeIntervals -- Determine time intervals for which each coach’s availability will be checked against.
AS
(
SELECT DISTINCT *
FROM (
SELECT MS.CoachID
,MS.BusyST
,MS.BusyET
,(
CASE
WHEN AC.Start < MS.BusyST THEN MS.BusyST
ELSE AC.Start
END
) AS [TS]
FROM #Temp1 MS
LEFT OUTER JOIN ActualAvailability AC ON (AC.CoachID <> MS.CoachID)
AND
(
( (MS.[BusyST] <= AC.[Start]) AND (MS.[BusyET] >= AC.[End]) ) OR -- Meeting covers entire work schedule
( (MS.[BusyST] > AC.[Start]) AND (MS.[BusyET] < AC.[End]) ) OR -- Meeting is contained with in work schedule
( (MS.[BusyST] < AC.[Start]) AND (MS.[BusyET] > AC.[Start]) AND ([MS].[BusyET] < AC.[End]) ) OR -- Meeting ends within work schedule (partial overlap)
( (MS.[BusyST] > AC.[Start]) AND (MS.[BusyST] < AC.[End]) AND ([MS].[BusyET] > AC.[End]) ) -- Meeting starts within work schedule (partial overlap)
)
UNION ALL
SELECT MS.CoachID
,MS.BusyST
,MS.BusyET
,(
CASE
WHEN AC.[End] > MS.BusyET THEN MS.BusyET
ELSE AC.[End]
END
) AS [TS]
FROM #Temp1 MS
LEFT OUTER JOIN ActualAvailability AC ON (AC.CoachID <> MS.CoachID)
AND
(
( (MS.[BusyST] <= AC.[Start]) AND (MS.[BusyET] >= AC.[End]) ) OR -- Meeting covers entire work schedule
( (MS.[BusyST] > AC.[Start]) AND (MS.[BusyET] < AC.[End]) ) OR -- Meeting is contained with in work schedule
( (MS.[BusyST] < AC.[Start]) AND (MS.[BusyET] > AC.[Start]) AND ([MS].[BusyET] < AC.[End]) ) OR -- Meeting ends within work schedule (partial overlap)
( (MS.[BusyST] > AC.[Start]) AND (MS.[BusyST] < AC.[End]) AND ([MS].[BusyET] > AC.[End]) ) -- Meeting starts within work schedule (partial overlap)
)
) Intervals
),AvailableCoachTimeSegments -- Determine each coach’s availability against each time interval being checked.
AS
(
SELECT ROW_NUMBER() OVER (PARTITION BY TI.CoachID ORDER BY TI.Start, AT.CoachID) AS RankAsc
,ROW_NUMBER() OVER (PARTITION BY TI.CoachID ORDER BY TI.[End] DESC, AT.CoachID DESC) AS RankDesc
,TI.CoachID
,TI.BusyST
,TI.BusyET
,TI.Start
,TI.[End]
,AT.CoachID AS AvailableCoachID
,AT.Start AS AvailableStart
,AT.[End] AS AvailableEnd
,(
CASE
WHEN (MIN(TI.[Start]) OVER (PARTITION BY TI.CoachID)) <> TI.BusyST THEN 1
ELSE 0
END
) AS StartIncomplete
,(
CASE
WHEN (MAX(TI.[End]) OVER (PARTITION BY TI.CoachID)) <> TI.BusyET THEN 1
ELSE 0
END
) AS EndIncomplete
FROM (
SELECT CoachID
,BusyST
,BusyET
,TS AS [Start]
,LEAD(TS, 1, TS) OVER (PARTITION BY CoachID ORDER BY TS) AS [End]
FROM TimeIntervals
) TI
LEFT OUTER JOIN ActualAvailability AT ON
(
( (AT.[Start] <= TI.[Start]) AND (AT.[End] >= TI.[End]) ) OR -- Coach availability covers entire time segment
( (AT.[Start] > TI.[Start]) AND (AT.[End] < TI.[End]) ) OR -- Coach availability is contained within the time segment
( (AT.[Start] < TI.[Start]) AND (AT.[End] > TI.[Start]) AND (AT.[End] < TI.[End]) ) OR -- Coach availability ends within the time segment (partial overlap)
( (AT.[Start] > TI.[Start]) AND (AT.[Start] < TI.[End]) AND (AT.[End] > TI.[End]) ) -- Coach availability starts within the time segment (partial overlap)
)
)
-- Final result
SELECT CoachID
,BusyST
,BusyET
,Start AS CanCoachST
,[End] AS CanCoachET
,COUNT(AvailableCoachID) AS NumOfCoaches
,ISNULL(STUFF((
SELECT TOP 100 PERCENT ', ' + CAST(AvailableCoach.AvailableCoachID AS VARCHAR(MAX))
FROM AvailableCoachTimeSegments AvailableCoach
WHERE (AvailableCoach.CoachID = Results.CoachID AND AvailableCoach.Start = Results.Start AND AvailableCoach.[End] = Results.[End])
ORDER BY AvailableCoach.AvailableCoachID
FOR XML PATH(''),TYPE).value('(./text())[1]','VARCHAR(MAX)')
,1,2,''), '(No one is available)') AS AvailableCoaches
FROM AvailableCoachTimeSegments Results
WHERE [Start] <> [End]
GROUP BY CoachID, BusyST, BusyET, Start, [End], StartIncomplete, EndIncomplete
UNION ALL -- Add any missing time segments at the start of the busy time or end of the busy time.
SELECT CoachID
,BusyST
,BusyET
,(
CASE
WHEN StartIncomplete = 1 THEN BusyST
WHEN EndIncomplete = 1 THEN MAX([End])
ELSE Start
END
) AS CanCoachST
,(
CASE
WHEN StartIncomplete = 1 THEN Start
WHEN EndIncomplete = 1 THEN BusyET
ELSE [End]
END
) AS CanCoachET
,0 AS NumOfCoaches
,'(No one is available)' AS AvailableCoaches
FROM AvailableCoachTimeSegments Results
WHERE [Start] <> [End] AND ( (StartIncomplete = 1 AND RankAsc = 1) OR (EndIncomplete = 1 AND RankDesc = 1) )
GROUP BY CoachID, BusyST, BusyET, Start, [End], StartIncomplete, EndIncomplete
ORDER BY CoachID, CanCoachST
DROP TABLE #Temp1
DROP TABLE #Temp2
This is your expected result that is taking into consideration of the Busy Coaches that overlap the Available Coaches.
| CoachID | CanCoachST | CanCoachET | NumOfCoaches | CanCoach |
|---------|------------------|------------------|--------------|----------|
| 1 | 2016-08-17 09:12 | 2016-08-17 09:24 | 2 | 2, 5 |
| 1 | 2016-08-17 09:24 | 2016-08-17 09:30 | 3 | 2, 3, 5 |
| 1 | 2016-08-17 09:30 | 2016-08-17 09:34 | 1 | 5 |
| 1 | 2016-08-17 09:34 | 2016-08-17 09:55 | 2 | 4, 5 |
| 1 | 2016-08-17 09:55 | 2016-08-17 10:00 | 1 | 4 |
| 1 | 2016-08-17 10:00 | 2016-08-17 10:11 | 2 | 3, 4 |
| 3 | 2016-08-17 09:30 | 2016-08-17 09:34 | 1 | 5 |
| 3 | 2016-08-17 09:34 | 2016-08-17 09:55 | 2 | 4, 5 |
| 3 | 2016-08-17 09:55 | 2016-08-17 10:00 | 1 | 4 |
| 4 | 2016-08-17 12:07 | 2016-08-17 12:27 | 2 | 1, 3 |
| 4 | 2016-08-17 12:27 | 2016-08-17 13:08 | 1 | 3 |
| 4 | 2016-08-17 13:08 | 2016-08-17 13:10 | 0 | NULL |
#Temp1 as Busy Coaches:
| CoachID | BusyST | BusyET |
|---------|------------------|------------------|
| 1 | 2016-08-17 09:12 | 2016-08-17 10:11 |
| 3 | 2016-08-17 09:30 | 2016-08-17 10:00 |
| 4 | 2016-08-17 12:07 | 2016-08-17 13:10 |
#Temp2 as Available Coaches:
| CoachID | AvailableST | AvailableET |
|---------|------------------|------------------|
| 1 | 2016-08-17 09:07 | 2016-08-17 11:09 |
| 1 | 2016-08-17 11:34 | 2016-08-17 12:27 |
| 2 | 2016-08-17 09:11 | 2016-08-17 09:30 |
| 3 | 2016-08-17 09:24 | 2016-08-17 13:08 |
| 4 | 2016-08-17 09:34 | 2016-08-17 13:00 |
| 5 | 2016-08-17 09:10 | 2016-08-17 09:55 |
The script below is a bit long.
;
with
st
(
CoachID,
CanCoachST
)
as
(
select
bound.CoachID,
s.BusyST
from
#Temp1 as s
cross apply
(
select
b.CoachID,
b.BusyST,
b.BusyET
from
#Temp1 as b
where 1 = 1
and s.BusyST between b.BusyST and b.BusyET
)
as bound
union all
select
bound.CoachID,
s.BusyET
from
#Temp1 as s
cross apply
(
select
b.CoachID,
b.BusyST,
b.BusyET
from
#Temp1 as b
where 1 = 1
and s.BusyET between b.BusyST and b.BusyET
and s.CoachID != b.CoachID
)
as bound
union all
select
bound.CoachID,
s.AvailableST
from
#Temp2 as s
cross apply
(
select
b.CoachID,
b.BusyST,
b.BusyET
from
#Temp1 as b
where 1 = 1
and s.AvailableST between b.BusyST and b.BusyET
)
as bound
union all
select
bound.CoachID,
s.AvailableET
from
#Temp2 as s
cross apply
(
select
b.CoachID,
b.BusyST,
b.BusyET
from
#Temp1 as b
where 1 = 1
and s.AvailableET between b.BusyST and b.BusyET
and s.CoachID != b.CoachID
)
as bound
),
d as
(
select distinct
CoachID,
CanCoachST
from
st
),
r as
(
select
row_number() over (order by CoachID, CanCoachST) as RowID,
CoachID,
CanCoachST
from
d
),
rng as
(
select
r1.RowID,
r1.CoachID,
r1.CanCoachST,
case when r1.CoachID = r2.CoachID
then r2.CanCoachST else t.BusyET end as CanCoachET
from
r as r1
left join
r as r2
on
r1.RowID = r2.RowID - 1
left join
#Temp1 as t
on
t.CoachID = r1.CoachID
),
c as
(
select
rng.RowID,
rng.CoachID,
rng.CanCoachST,
rng.CanCoachET,
t2.CoachID as CanCoachID
from
rng
cross join
#Temp1 as t1
cross join
#Temp2 as t2
where 1 = 1
and t2.CoachID != rng.CoachID
and t2.AvailableST <= rng.CanCoachST
and t2.AvailableET >= rng.CanCoachET
),
b as
(
select
rng.RowID,
rng.CoachID,
rng.CanCoachST,
rng.CanCoachET,
t1.CoachID as BusyCoachID
from
rng
cross join
#Temp1 as t1
where 1 = 1
and t1.CoachID != rng.CoachID
and t1.BusyST <= rng.CanCoachST
and t1.BusyET >= rng.CanCoachET
),
e as
(
select
c.RowID,
c.CoachID,
c.CanCoachST,
c.CanCoachET,
c.CanCoachID
from
c
except
select
b.RowID,
b.CoachID,
b.CanCoachST,
b.CanCoachET,
b.BusyCoachID
from
b
),
f as
(
select
rng.RowID,
rng.CoachID,
rng.CanCoachST,
rng.CanCoachET,
e.CanCoachID
from
rng
left join
e
on
e.RowID = rng.RowID
)
select
f.CoachID,
f.CanCoachST,
f.CanCoachET,
count(f.CanCoachID) as NumOfCoaches,
stuff
(
(
select ', ' + cast(f1.CanCoachID as varchar(5))
from f as f1 where f1.RowID = f.RowID
for xml path('')
),
1, 2, ''
)
as CanCoach
from
f
group by
f.RowID,
f.CoachID,
f.CanCoachST,
f.CanCoachET
order by
1, 2

Querying DAU/MAU over time (daily)

I have a daily sessions table with columns user_id and date. I'd like to graph out DAU/MAU (daily active users / monthly active users) on a daily basis. For example:
Date MAU DAU DAU/MAU
2014-06-01 20,000 5,000 20%
2014-06-02 21,000 4,000 19%
2014-06-03 20,050 3,050 17%
... ... ... ...
Calculating daily active users is straightforward but calculating the monthly active users e.g. the number of users that logged in today minus 30 days, is causing problems. How is this achieved without a left join for each day?
Edit: I'm using Postgres.
Assuming you have values for each day, you can get the total counts using a subquery and range between:
with dau as (
select date, count(userid) as dau
from dailysessions ds
group by date
)
select date, dau,
sum(dau) over (order by date rows between -29 preceding and current row) as mau
from dau;
Unfortunately, I think you want distinct users rather than just user counts. That makes the problem much more difficult, especially because Postgres doesn't support count(distinct) as a window function.
I think you have to do some sort of self join for this. Here is one method:
with dau as (
select date, count(distinct userid) as dau
from dailysessions ds
group by date
)
select date, dau,
(select count(distinct user_id)
from dailysessions ds
where ds.date between date - 29 * interval '1 day' and date
) as mau
from dau;
This one uses COUNT DISTINCT to get the rolling 30 days DAU/MAU:
(calculating reddit's user engagement in BigQuery - but the SQL is standard enough to be used on other databases)
SELECT day, dau, mau, INTEGER(100*dau/mau) daumau
FROM (
SELECT day, EXACT_COUNT_DISTINCT(author) dau, FIRST(mau) mau
FROM (
SELECT DATE(SEC_TO_TIMESTAMP(created_utc)) day, author
FROM [fh-bigquery:reddit_comments.2015_09]
WHERE subreddit='AskReddit') a
JOIN (
SELECT stopday, EXACT_COUNT_DISTINCT(author) mau
FROM (SELECT created_utc, subreddit, author FROM [fh-bigquery:reddit_comments.2015_09], [fh-bigquery:reddit_comments.2015_08]) a
CROSS JOIN (
SELECT DATE(SEC_TO_TIMESTAMP(created_utc)) stopday
FROM [fh-bigquery:reddit_comments.2015_09]
GROUP BY 1
) b
WHERE subreddit='AskReddit'
AND SEC_TO_TIMESTAMP(created_utc) BETWEEN DATE_ADD(stopday, -30, 'day') AND TIMESTAMP(stopday)
GROUP BY 1
) b
ON a.day=b.stopday
GROUP BY 1
)
ORDER BY 1
I went further at How to calculate DAU/MAU with BigQuery (engagement)
I've written about this on my blog.
The DAU is easy, as you noticed. You can solve the MAU by first creating a view with boolean values for when a user activates and de-activates, like so:
CREATE OR REPLACE VIEW "vw_login" AS
SELECT *
, LEAST (LEAD("date") OVER w, "date" + 30) AS "activeExpiry"
, CASE WHEN LAG("date") OVER w IS NULL THEN true ELSE false AS "activated"
, CASE
WHEN LEAD("date") OVER w IS NULL THEN true
WHEN LEAD("date") OVER w - "date" > 30 THEN true
ELSE false
END AS "churned"
, CASE
WHEN LAG("date") OVER w IS NULL THEN false
WHEN "date" - LAG("date") OVER w <= 30 THEN false
WHEN row_number() OVER w > 1 THEN true
ELSE false
END AS "resurrected"
FROM "login"
WINDOW w AS (PARTITION BY "user_id" ORDER BY "date")
This creates boolean values per user per day when they become active, when they churn and when they re-activate.
Then do a daily aggregate of the same:
CREATE OR REPLACE VIEW "vw_activity" AS
SELECT
SUM("activated"::int) "activated"
, SUM("churned"::int) "churned"
, SUM("resurrected"::int) "resurrected"
, "date"
FROM "vw_login"
GROUP BY "date"
;
And finally calculate running totals of active MAUs by calculating the cumulative sums over the columns. You need to join the vw_activity twice, since the second one is joined to the day when the user becomes inactive (i.e. 30 days since their last login).
I've included a date series in order to ensure that all days are present in your dataset. You can do without it too, but you might skip days in your dataset.
SELECT
d."date"
, SUM(COALESCE(a.activated::int,0)
- COALESCE(a2.churned::int,0)
+ COALESCE(a.resurrected::int,0)) OVER w
, d."date", a."activated", a2."churned", a."resurrected" FROM
generate_series('2010-01-01'::date, CURRENT_DATE, '1 day'::interval) d
LEFT OUTER JOIN vw_activity a ON d."date" = a."date"
LEFT OUTER JOIN vw_activity a2 ON d."date" = (a2."date" + INTERVAL '30 days')::date
WINDOW w AS (ORDER BY d."date") ORDER BY d."date";
You can of course do this in a single query, but this helps understand the structure better.
You didn't show us your complete table definition, but maybe something like this:
select date,
count(*) over (partition by date_trunc('day', date) order by date) as dau,
count(*) over (partition by date_trunc('month', date) order by date) as mau
from sessions
order by date;
To get the percentage without repeating the window functions, just wrap this in a derived table:
select date,
dau,
mau,
dau::numeric / (case when mau = 0 then null else mau end) as pct
from (
select date,
count(*) over (partition by date_trunc('day', date) order by date) as dau,
count(*) over (partition by date_trunc('month', date) order by date) as mau
from sessions
) t
order by date;
Here is an example output:
postgres=> select * from sessions;
session_date | user_id
--------------+---------
2014-05-01 | 1
2014-05-01 | 2
2014-05-01 | 3
2014-05-02 | 1
2014-05-02 | 2
2014-05-02 | 3
2014-05-02 | 4
2014-05-02 | 5
2014-06-01 | 1
2014-06-01 | 2
2014-06-01 | 3
2014-06-02 | 1
2014-06-02 | 2
2014-06-02 | 3
2014-06-02 | 4
2014-06-03 | 1
2014-06-03 | 2
2014-06-03 | 3
2014-06-03 | 4
2014-06-03 | 5
(20 rows)
postgres=> select session_date,
postgres-> dau,
postgres-> mau,
postgres-> round(dau::numeric / (case when mau = 0 then null else mau end),2) as pct
postgres-> from (
postgres(> select session_date,
postgres(> count(*) over (partition by date_trunc('day', session_date) order by session_date) as dau,
postgres(> count(*) over (partition by date_trunc('month', session_date) order by session_date) as mau
postgres(> from sessions
postgres(> ) t
postgres-> order by session_date;
session_date | dau | mau | pct
--------------+-----+-----+------
2014-05-01 | 3 | 3 | 1.00
2014-05-01 | 3 | 3 | 1.00
2014-05-01 | 3 | 3 | 1.00
2014-05-02 | 5 | 8 | 0.63
2014-05-02 | 5 | 8 | 0.63
2014-05-02 | 5 | 8 | 0.63
2014-05-02 | 5 | 8 | 0.63
2014-05-02 | 5 | 8 | 0.63
2014-06-01 | 3 | 3 | 1.00
2014-06-01 | 3 | 3 | 1.00
2014-06-01 | 3 | 3 | 1.00
2014-06-02 | 4 | 7 | 0.57
2014-06-02 | 4 | 7 | 0.57
2014-06-02 | 4 | 7 | 0.57
2014-06-02 | 4 | 7 | 0.57
2014-06-03 | 5 | 12 | 0.42
2014-06-03 | 5 | 12 | 0.42
2014-06-03 | 5 | 12 | 0.42
2014-06-03 | 5 | 12 | 0.42
2014-06-03 | 5 | 12 | 0.42
(20 rows)
postgres=>

SQL duration between two dates in different rows

I would really appreciate some assistance if somebody could help me construct a MSSQL Server 2000 query that would return the duration between a customer's A entry and their B entry.
Not all customers are expected to have a B record and so no results would be returned.
Customers Audit
+---+---------------+---+----------------------+
| 1 | Peter Griffin | A | 2013-01-01 15:00:00 |
| 2 | Martin Biggs | A | 2013-01-02 15:00:00 |
| 3 | Peter Griffin | C | 2013-01-05 09:00:00 |
| 4 | Super Mario | A | 2013-01-01 15:00:00 |
| 5 | Martin Biggs | B | 2013-01-03 18:00:00 |
+---+---------------+---+----------------------+
I'm hoping for results similar to:
+--------------+----------------+
| Martin Biggs | 1 day, 3 hours |
+--------------+----------------+
Something like the below (don't know your schema, so you'll need to change names of objects) should suffice.
SELECT ABS(DATEDIFF(HOUR, CA.TheDate, CB.TheDate)) AS HoursBetween
FROM dbo.Customers CA
INNER JOIN dbo.Customers CB
ON CB.Name = CA.Name
AND CB.Code = 'B'
WHERE CA.Code = 'A'
SELECT A.CUSTOMER, DATEDIFF(HOUR, A.ENTRY_DATE, B.ENTRY_DATE) DURATION
FROM CUSTOMERSAUDIT A, CUSTOMERSAUDIT B
WHERE B.CUSTOMER = A.CUSTOMER AND B.ENTRY_DATE > A.ENTRY_DATE
This is Oracle query but all features available in MS Server as far as I know. I'm sure I do not have to tell you how to concatenate the output to get desired result. All values in output will be in separate columns - days, hours, etc... And it is not always easy to format the output here:
SELECT id, name, grade
, NVL(EXTRACT(DAY FROM day_time_diff), 0) days
, NVL(EXTRACT(HOUR FROM day_time_diff), 0) hours
, NVL(EXTRACT(MINUTE FROM day_time_diff), 0) minutes
, NVL(EXTRACT(SECOND FROM day_time_diff), 0) seconds
FROM
(
SELECT id, name, grade
, (begin_date-end_date) day_time_diff
FROM
(
SELECT id, name, grade
, CAST(start_date AS TIMESTAMP) begin_date
, CAST(end_date AS TIMESTAMP) end_date
FROM
(
SELECT id, name, grade, start_date
, LAG(start_date, 1, to_date(null)) OVER (ORDER BY id) end_date
FROM stack_test
)
)
)
/
Output:
ID NAME GRADE DAYS HOURS MINUTES SECONDS
------------------------------------------------------------
1 Peter Griffin A 0 0 0 0
2 Martin Biggs A 1 1 0 0
3 Peter Griffin C 2 17 0 0
4 Super Mario A -3 -18 0 0
5 Martin Biggs A 2 3 0 0
The table structure/columns I used - it would be great if you took care of this and data in advance:
CREATE TABLE stack_test
(
id NUMBER
,name VARCHAR2(50)
,grade VARCHAR2(3)
,start_date DATE
)
/