I have the following schema and related data.
-- Schema
CREATE TABLE [PERSON] (
[id] int NOT NULL,
[first_name] varchar(50) NOT NULL,
[last_name] varchar (50) NOT NULL
CONSTRAINT [PK__PERSON] PRIMARY KEY ([id])
)
GO
CREATE TABLE [EVENT] (
[id] int NOT NULL,
[name] varchar(50) NOT NULL
CONSTRAINT [PK__EVENT] PRIMARY KEY ([id])
)
GO
CREATE TABLE [EVENT_PARTICIPANT] (
[event_id] int NOT NULL,
[person_id] int NOT NULL
CONSTRAINT [PK__EVENT_PARTICIPANT] PRIMARY KEY ([event_id], [person_id])
)
GO
ALTER TABLE [EVENT_PARTICIPANT] ADD CONSTRAINT [FK__EVENT__EVENT_PARTICIPANT__event_id]
FOREIGN KEY ([event_id])
REFERENCES [EVENT]([id])
GO
ALTER TABLE [EVENT_PARTICIPANT] ADD CONSTRAINT [FK__PERSON__EVENT_PARTICIPANT__person_id]
FOREIGN KEY ([person_id])
REFERENCES [PERSON]([id])
GO
-- data
INSERT INTO [PERSON] VALUES(1, 'Alpha', 'A')
INSERT INTO [PERSON] VALUES(2, 'Bravo', 'B')
INSERT INTO [PERSON] VALUES(3, 'Charlie', 'C')
INSERT INTO [PERSON] VALUES(4, 'Delta', 'D')
INSERT INTO [PERSON] VALUES(5, 'Echo', 'E')
INSERT INTO [PERSON] VALUES(6, 'Foxtrot', 'F')
INSERT INTO [PERSON] VALUES(7, 'Golf', 'G')
INSERT INTO [PERSON] VALUES(8, 'Hotel', 'H')
INSERT INTO [PERSON] VALUES(9, 'India', 'I')
INSERT INTO [PERSON] VALUES(10, 'Juliet', 'J')
GO
INSERT INTO [EVENT] VALUES(1, 'Event A')
INSERT INTO [EVENT] VALUES(2, 'Event B')
INSERT INTO [EVENT] VALUES(3, 'Event C')
INSERT INTO [EVENT] VALUES(4, 'Event D')
INSERT INTO [EVENT] VALUES(5, 'Event E')
INSERT INTO [EVENT] VALUES(6, 'Event F')
INSERT INTO [EVENT] VALUES(7, 'Event G')
INSERT INTO [EVENT] VALUES(8, 'Event H')
INSERT INTO [EVENT] VALUES(9, 'Event I')
INSERT INTO [EVENT] VALUES(10, 'Event J')
GO
INSERT INTO [EVENT_PARTICIPANT] VALUES(1,1)
INSERT INTO [EVENT_PARTICIPANT] VALUES(1,2)
INSERT INTO [EVENT_PARTICIPANT] VALUES(1,3)
INSERT INTO [EVENT_PARTICIPANT] VALUES(2,4)
INSERT INTO [EVENT_PARTICIPANT] VALUES(2,5)
INSERT INTO [EVENT_PARTICIPANT] VALUES(2,6)
INSERT INTO [EVENT_PARTICIPANT] VALUES(3,5)
INSERT INTO [EVENT_PARTICIPANT] VALUES(3,6)
INSERT INTO [EVENT_PARTICIPANT] VALUES(4,1)
INSERT INTO [EVENT_PARTICIPANT] VALUES(4,4)
INSERT INTO [EVENT_PARTICIPANT] VALUES(5,1)
INSERT INTO [EVENT_PARTICIPANT] VALUES(6,7)
INSERT INTO [EVENT_PARTICIPANT] VALUES(7,8)
INSERT INTO [EVENT_PARTICIPANT] VALUES(8,9)
GO
I need to find all the conflicting events where there are matching participants such that the query returns for each event a list of events conflicting with it. The matching does not have to be 100% Even if one person matches, that means the events are conflicting with each other.
I’ve already generated a comma separated list of event participants for each event, but struggling a little with how to write an efficient query to get the conflicting event for SQL Server 2008.
Thanks!
You could try with this query:
select distinct ep1.event_id,ep2.event_idfrom EVENT_PARTICIPANT ep1
inner join EVENT_PARTICIPANT ep2 on ep1.person_id=ep2.person_id
where ep1.event_id <> ep2.event_id
order by 1,2