How do I remove duplicate entries in this T-SQL query containing LEFT OUTER JOIN
I am having issues taking out duplicate entries from this query containing multiple LEFT OUTER JOINs
SELECT s.Category,
SUM(spons.SPONS) AS SPONSOREDAMT,
SUM(priv.PRIV) AS PRIVATEAMT FROM (SELECT ID AS ID,
Name AS Category FROM dbo.ServicesTable) s
LEFT OUTER JOIN (SELECT DISTINCT ( ServiceId ) AS ServiceId,
DateCreated,
SUM(SPONSORAMT) AS SPONS
FROM dbo.SponsorMonthlyBill
GROUP BY ServiceId,
DateCreated) spons
ON ( s.ID = spons.ServiceId )
LEFT OUTER JOIN (SELECT DISTINCT ( ServiceId ) AS ServiceId,
DateCreated,
SUM(PRIVATEAMT) AS PRIV
FROM dbo.PrivateMonthlyBill
GROUP BY ServiceId,
DateCreated) priv
ON ( s.ID = priv.ServiceId )
AND ( MONTH(priv.DateCreated) = MONTH('2011-08-04') )
GROUP BY s.Category,
spons.SPONS,
priv.PRIV
If I make last line look like this:
GROUP BY s.Category
instead of what its now, I'll have the duplicate entries adding up. If there are more than double entries, all 3 or 4 or more get added up. So how go about this.
Scorpi0 gave an answer which worked but needs some extra modification. This was the modification I made to it:
SELECT s.Name AS Category,
SUM(spons.SPONS) AS SPONSOREDAMT,
SUM(priv.PRIV) AS PRIVATEAMT, SUM(spons.SPONS) + SUM(priv.PRIV) as
TOTAL,spons.DateCreated
FROM dbo.ServicesTable s
LEFT OUTER JOIN (SELECT ServiceId,DateCreated,
开发者_开发技巧 SUM(SPONSORAMT) AS SPONS
FROM dbo.SponsorMonthlyBill
GROUP BY ServiceId,DateCreated) spons
ON ( s.ID = spons.ServiceId )
LEFT OUTER JOIN (SELECT distinct ServiceId,
SUM(PRIVATEAMT) AS PRIV
FROM dbo.PrivateMonthlyBill
GROUP BY ServiceId
) priv
ON ( s.ID = priv.ServiceId )
GROUP BY s.Name,spons.DateCreated
I know it introduced the duplicates again but how can keep the DateCreated
out of GROUP BY and still access it in the main SELECT clause? Please keep in mind that this is a View and there are some rules that it insists must be followed.
Your duplicates are coming from your useless group by DateCreated.
Try with this query, it should give you the right results:
SELECT s.Name AS Category,
SUM(spons.SPONS) AS SPONSOREDAMT,
SUM(priv.PRIV) AS PRIVATEAMT
FROM dbo.ServicesTable s
LEFT OUTER JOIN (SELECT ServiceId,
SUM(SPONSORAMT) AS SPONS
FROM dbo.SponsorMonthlyBill
GROUP BY ServiceId) spons
ON ( s.ID = spons.ServiceId )
LEFT OUTER JOIN (SELECT ServiceId
SUM(PRIVATEAMT) AS PRIV
FROM dbo.PrivateMonthlyBill
WHERE MONTH(DateCreated) = MONTH('2011-08-04')
GROUP BY ServiceId
) priv
ON ( s.ID = priv.ServiceId )
GROUP BY s.Name
精彩评论