在SQL中连接多个表并执行算术运算

时间:2014-10-03 02:47:26

标签: mysql sql database

我需要SQL查询的帮助。

数据库表示例: 疾病:http://i57.tinypic.com/qn1fg6.png 面试:http://i60.tinypic.com/4smrk9.png

我的查询如下:

SELECT interview.locationOfInterview as City, count(diseases.diseaseName) as diseaseTotal 
from diseases 
INNER JOIN interview on diseases.pID=interview.personInterviewed 
where interview.dateOfInterview = 2012 and diseases.diseaseName='asthma' 
group by interview.locationOfInterview

它给出了以下结果:

City  | diseaseTotal
Littleplace | 2
Smallville | 3

此查询通过并计算疾病哮喘在疾病表中出现的次数,并将其与另一个名为访谈的表格相关联,该表格包含城市。它计算每个城市发生哮喘的次数。

接下来,我有另一个查询通过表并计算总体并给出以下结果。

查询:

SELECT locationOfInterview, count(*)*200 Total from interview group by locationOfInterview

结果:

City | Population
Farmland | 1800
Littleplace | 3000
Smallville | 2400

对于这个具体的问题,我需要保持疾病的数量,看看2012年每个城市发生哮喘的次数,但人口应该是全年,2012-2014。

这两个查询都执行了正确的操作并给出了正确的结果,但我需要找到一种方法将它们组合在一起,这样我就可以将城市疾病总数除以城市人口,以便让我流行。

我想出了以下查询,但是它在人口中使用了where子句,而且只给了我2012年所有人的人口而不是所有年份(2012-2014)

查询:

SELECT interview.locationOfInterview as City, count(interview.locationOfInterview)*200 as Population, diseases.diseaseName as DiseaseName, count(diseases.diseaseName) as Disease Occurance
from diseases 
INNER JOIN interview on diseases.pID=interview.personInterviewed 
where interview.dateOfInterview = 2012 and diseases.diseaseName='asthma' 
group by interview.locationOfInterview

结果:

City | Population | Disease Name | Disease Occurance
Littleplace | 400 | Asthma | 2
Smallville | 600 | Asthma | 3

我需要的结果是:

City | Population | Disease Name | Disease Occurance
Littleplace | 3000 | Asthma | 2
Smallville | 2400 | Asthma | 3

之后我可以弄明白如何进行分工。我只是遇到了一个问题,因为where = 2012限制了人口。

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

我认为你可以使用条件聚合做你想做的事情:

SELECT i.locationOfInterview as City,
       sum(case when i.DateOfInterview = 2012 and d.diseaseName is not null then 1 else 0 end) as diseaseTotal,
       count(*) * 200,
       (sum(case when i.DateOfInterview = 2012 and d.diseaseName is not null then 1 else 0 end) /
        count(*) * 200
       )
from interview i left join
     diseases d 
     on d.pID = i.personInterviewed and d.diseaseName = 'asthma'
where i.dateOfInterview = 2012 and 
group by i.locationOfInterview;