我正在努力查询需要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
感谢所有贡献的人!
Russell Schutte
答案 0 :(得分:8)
如果您只想要一个整体数字,请尝试
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
答案 1 :(得分:3)
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
这取决于您的数据库服务器,这比执行子选择更有效。
答案 2 :(得分:2)
一个简单的答案是使用“分组依据”。 Group by与distinct相同的字段具有相同的效果,但允许您使用聚合函数。您可以在分组后添加“Having”子句,以过滤您想要查看的记录。