I\'m struggling with a query where I need to SUM DISTINCT Rows. There has to be a way to do this... but I\'m lost.
Here\'s what I\'ve got:
SELECT D
An easy answer is use "group by". Group by has the same effect with the same fields as distinct, but allows you to use aggregate functions. You can add a "Having" clause after the group by to filter what records you would like to see.
Use GROUP BY along with the SUM() and COUNT() aggregates.
SELECT count(*) as totalRows, Zipcodes.CountyID,
sum(us_co_est2005_allData.PopEstimate2005) as SumPopEstimate2005,
sum(us_co_est2005_allData.EstimatesBase2000) as SumEstimatesBase2000,
users_link_territory.userID
FROM
Zipcodes Inner Join Users_link_territory ON zipcodes.CountyID =
Users_link_territory.CountyID Inner Join
us_co_est2005_alldata ON zipcodes.FIPS = us_co_est2005_alldata.State AND zipcodes.code = us_co_est2005_alldata.County
WHERE (users_link_territory.userid = 4)
GROUP BY Zipcodes.CountyID,users_link_territory.userID
Depending on your db server, this will be more efficient than doing a sub-select.
If you just want an overall figure for it try
select sum(PopEstimate2005), sum(EstimatesBase2000)
from(
SELECT Distinct
Zipcodes.CountyID,
us_co_est2005_allData.PopEstimate2005,
us_co_est2005_allData.EstimatesBase2000,
users_link_territory.userID
FROM
Zipcodes Inner Join
Users_link_territory ON zipcodes.CountyID = Users_link_territory.CountyID Inner Join
us_co_est2005_alldata ON zipcodes.FIPS = us_co_est2005_alldata.State AND zipcodes.code = us_co_est2005_alldata.County
WHERE
(users_link_territory.userid = 4)
) as foo