[MS SQL] Getting a count before JOIN's
I'm not entirely sure how to phrase my question, which has made finding the answer on SO a bit difficult.
I have a query that prepares a report, grouping by a facility and month, and summarizing flags on related tables. It looks something like:
SELECT dbo.Facilities.FacilityId AS FacilityId,
CAST(CAST(YEAR(Incidents.IncidentDate) AS VARCHAR(4)) + RIGHT('0' + CAST(MONTH(Incidents.IncidentDate) AS VARCHAR(2)), 2) + RIGHT('0' + CAST(1 AS VARCHAR(2)), 2) AS DATETIME) AS Date,
COUNT(Incidents.IncidentId) AS 'All',
SUM(CASE dbo.IncidentIncidentTypes.IncidentType WHEN 1 THEN 1 ELSE 0 END) Falls,
....
additional columns omitted
FROM Incidents
JOIN dbo.IncidentIncidentTypes ON Incidents.IncidentId = IncidentIncidentTypes.IncidentId
JOIN dbo.IncidentInjuryTypes ON Incidents.IncidentId = IncidentInjuryTypes.IncidentId
JOIN dbo.IncidentTreatments ON Incidents.IncidentId = IncidentTreatments.IncidentId
JOIN dbo.IncidentActionTakens ON Incidents.IncidentId = IncidentActionTakens.IncidentId
JOIN dbo.Facilities ON Incidents.FacilityId = Facilities.FacilityId
GROUP BY Facilities.FacilityId, YEAR(Incidents.IncidentDate), MONTH(Incidents.IncidentDate)
This might be a simple question, but I'm not sure how to get the "top level" count of Incidents (the All column). Instead, it seems to be taking the count of all the rows in my first JOIN. I've tried using DISTINCT with COUNT(DISTINCT Incidents.IncidentId), but that doesn't work either.
Any help is greatly appreciated!
8 comments · 74% upvoted · other discussions
Use a subquery
http://technet.microsoft.com/en-us/library/ms189575%28v=sql.105%29.aspx