I have a set of users that register when they're available for particular meetings (slots). I have them mapped to each other and need to fill in the first available slot they can both meet, without double-booking them.
I have included an example of how I got to where I am solving it, but I'm stuck on how to get further.
CREATE TABLE #Slot (slot int, start datetime)
INSERT INTO #Slot VALUES (11, DATEADD(hour, 1, '1/1/1900 7:00:00'))
INSERT INTO #Slot VALUES (22, DATEADD(hour, 2, '1/1/1900 7:00:00'))
INSERT INTO #Slot VALUES (31, DATEADD(hour, 3, '1/1/1900 7:00:00'))
INSERT INTO #Slot VALUES (44, DATEADD(hour, 4, '1/1/1900 7:00:00'))
INSERT INTO #Slot VALUES (56, DATEADD(hour, 5, '1/1/1900 7:00:00'))
INSERT INTO #Slot VALUES (61, DATEADD(hour, 6, '1/1/1900 7:00:00'))
INSERT INTO #Slot VALUES (77, DATEADD(hour, 7, '1/1/1900 7:00:00'))
INSERT INTO #Slot VALUES (83, DATEADD(hour, 8, '1/1/1900 7:00:00'))
CREATE TABLE #Av (reg int, slot int)
INSERT INTO #Av
SELECT 1, slot
FROM #Slot
INSERT INTO #Av
SELECT 2, slot
FROM #Slot
INSERT INTO #Av
SELECT 3, slot
FROM #Slot
INSERT INTO #Av
SELECT 4, slot
FROM #Slot
CREATE TABLE #Met (reg1 int, reg2 int, slot int)
INSERT INTO #Met (reg1, reg2) VALUES (1, 2)
INSERT INTO #Met (reg1, reg2) VALUES (1, 3)
INSERT INTO #Met (reg1, reg2) VALUES (4, 2)
What I End up with using the following CTE is all times they can meet, but I don't know how to only end up with three rows. What I expect to end up with (using the data provided) is this:
reg1 reg2 slot
1 2 11
1 3 22 --since 1 is meeting with 2 already in slot 11
4 2 22 --since 2 is meeting with 1 already in slot 11
Here's what I have so far...basically all options, but cannot get down to the three rows:
with poss(opt, r1, r2, slot) AS
(
SELECT
ROW_NUMBER() OVER(PARTITION BY m.reg1, m.reg2 ORDER BY s1.start),
m.reg1, m.reg2, s1.slot
FROM #Met m
INNER JOIN #Av r1 ON m.reg1 = r1.reg
INNER JOIN #Slot s1 ON r1.slot = s1.slot
INNER JOIN #Av r2 ON m.reg2 = r2.reg
INNER JOIN #Slot s2 ON r2.slot = s2.slot
WHERE r1.slot = r2.slot
)
SELECT
*
FROM poss e
INNER JOIN #met m ON e.r1 = m.reg1 AND e.r2 = m.reg2
ORDER BY opt