我正在努力查询需要SUM DISTINCT Rows的查询.必须有办法做到这一点……但我迷路了.
这是我得到的:
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)
这给了我34行,为每个属于userid4的县提供不同的人口数量,但我如何得到PopEstimate2005和EstimatesBase2000的SUM?
像(但这不是一个合法的查询):
SELECT DISTINCT Zipcodes.CountyID,SUM(us_co_est2005_allData.PopEstimate2005) AS Population2005,SUM(us_co_est2005_allData.EstimatesBase2000) AS Population2000,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 users_link_territory.userid
当然,只要我将Zipcodes.CountyID添加到GroupBy的末尾,我就会再次回到我的34行.
非常感谢您的帮助.
拉塞尔舒特
.
.
.
.
.
获得以下帮助后 – 特别是Robb的帮助 – 我能够得到我真正想要的东西 – 在一个查询中总共有每个UserID的人口详细信息:
SELECT SUM(POPESTIMATE2005) AS Expr1,SUM(ESTIMATESBASE2000) AS Expr2,UserID 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 ) As FOO GROUP BY UserID
谢谢大家的贡献!
拉塞尔舒特
解决方法
如果你只是想要一个整体数字尝试
select sum(PopEstimate2005),sum(EstimatesBase2000) from( SELECT Distinct Zipcodes.CountyID,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