This problem has been sending me insane, although admittedly I’ve not written SQL for a long time.
I have 2 tables:
CREATE TABLE [Entities].[Events](
[EventID] [int] IDENTITY(1,1) NOT NULL,
[EventVenueID] [int] NULL,
[EntityID] [int] NOT NULL,
[OrganisationID] [int] NULL,
[Title] [nvarchar](300) NOT NULL,
[DateStart] [datetime] NOT NULL,
[DateFinish] [datetime] NOT NULL,
[Notes] [nvarchar](max) NULL,
[MinimumProviders] [int] NOT NULL,
[MinimumAttendees] [int] NOT NULL,
[ShowCalendar] [bit] NOT NULL,
[CreationDate] [datetime] NOT NULL,
[IsEnabled] [bit] NOT NULL)
CREATE TABLE [Entities].[EventParticipants](
[ParticipantID] [int] IDENTITY(1,1) NOT NULL,
[EventID] [int] NOT NULL,
[PersonID] [int] NOT NULL,
[ParticipantType] [int] NOT NULL,
[ParticipantStatus] [int] NOT NULL,
[AttendanceStatus] [int] NULL)
And a query:
SELECT
e.EventID,
ev.VenueName,
e.EntityID,
o.Name AS 'Organisation',
e.Title,
e.DateStart,
e.DateFinish,
e.Notes,
e.MinimumProviders,
e.MinimumAttendees,
e.CreationDate,
COUNT(epp.ParticipantID) AS 'ProvidersConfirmed',
COUNT(epa.ParticipantID) AS 'AttendeesConfirmed',
e.IsEnabled
FROM
Entities.Events e
LEFT OUTER JOIN
Entities.EventVenues ev
ON
e.EventVenueID = ev.EventVenueID
LEFT OUTER JOIN
Entities.Organisations o
ON
e.OrganisationID = o.OrganisationID
LEFT OUTER JOIN
Entities.EventParticipants epp
ON
e.EventID = epp.EventID AND epp.ParticipantType = 1 AND epp.ParticipantStatus = 3
LEFT OUTER JOIN
Entities.EventParticipants epa
ON
e.EventID = epa.EventID AND epa.ParticipantType = 2 AND epa.ParticipantStatus = 3
GROUP BY
e.EventID,
ev.VenueName,
e.EntityID,
o.Name,
e.Title,
e.DateStart,
e.DateFinish,
e.Notes,
e.MinimumProviders,
e.MinimumAttendees,
e.CreationDate,
e.IsEnabled
The count is producing strange results, for example in the EventParticipants table I have the following data:
Participant Type = 1 (3 records)
Participant Type = 2 (1 record)
Participant Status = 3 (4 records)
The queries count should return:
ProvidersConfirmed = 3
AttendeesConfirmed = 1
However, it’s returning
ProvidersConfirmed = 3
AttendeesConfirmed = 3
Can anyone help?
Basically all your joins are throwing off this query. When you join from
EventtoEventParticipantsThere is one event record and three EventParticipant records, this equates to three duplicate eventIDs in your dataset. Then you join toEventParticipantsagain. Because you’re joining 3 rows with one row, you get the result repeated 3 times.There are ways to trim down the results, but it would probably be better to only
JOINonce and do some selective math in your aggregate, like this:And SQL’s
COUNTwill throw away all the null values so it will only count unique values.