从两个表合计sql计算速率

6jygbczu  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(317)

我从两个不同的表格中计算出总数,试图找出犯罪率与人口的关系。
这是我的密码:

SELECT SUM(INCIDENT_BY_REGION.Total) AS TotalCrime, 
SUM(REGION.Population) AS TotalPopulation,
(TotalCrime/TotalPopulation) AS Rate
FROM INCIDENT_BY_REGION JOIN REGION
ON INCIDENT_BY_REGION.RegionID = REGION.RegionID;

但我犯了个错误,
错误代码1054:字段列表中的未知列“totalcrime”
.
我想要的是找出人口犯罪率。有什么建议吗?

4urapxun

4urapxun1#

请尝试下面,你不应该使用别名,而计算费率。而且,当表达式 sum(region.population) = 0 避免 divide by zero 错误:

SELECT SUM(INCIDENT_BY_REGION.Total) AS TotalCrime, 
SUM(REGION.Population) AS TotalPopulation,
case when SUM(REGION.Population) > 0 then 
          SUM(INCIDENT_BY_REGION.Total)/SUM(REGION.Population)
     else 0 end AS Rate
FROM INCIDENT_BY_REGION JOIN REGION
ON INCIDENT_BY_REGION.RegionID = REGION.RegionID;

相关问题