I have multiple left joins that i need to aggregate and denormalize data As shown is this example i get SUM of 3 FA instead 1 FA by F.
example: https://rextester.com/FOO264444
SELECT
SUM(CASE WHEN fa.PFId=1111 and fa.AcId=2 THEN 1 ELSE 0 END) as conditionalcountall
FROM #Fan f
LEFT JOIN #PF pf
ON pf.FId = f.Id
LEFT JOIN #LPe lip
ON lip.Id = pf.PId
LEFT JOIN #FA fa
ON fa.PFId = pf.Id
LEFT JOIN #Ac a
ON a.Id = fa.AcId
LEFT JOIN #DelAc das
ON das.PFId = pf.Id
LEFT JOIN #DAc da
ON da.Id = das.DAId
-------------------------
id |conditionalcountall |
-------------------------
1 3 |
-------------------------
When i remove the the last 2 Left Joins it gives the desired output of 1. But i need these 2 joins to aggregate other data from those 2 tables.
SELECT
SUM(CASE WHEN fa.ProfileFanId=1111 and fa.ActivityId=2 THEN 1 ELSE 0 END) as conditionalcountall
FROM #Fan f
LEFT JOIN #ProfileFan pf
ON pf.FanId = f.Id
LEFT JOIN #LinkedInProfile lip
ON lip.Id = pf.ProfileId
LEFT JOIN #FanActivity fa
ON fa.ProfileFanId = pf.Id
LEFT JOIN #Activity a
ON a.Id = fa.ActivityId
id |conditionalcountall |
-------------------------
1 | 1 |
-------------------------
What am I doing wrong?