【问题标题】:Join Multiple Tabls in SQL and Perform Arithmetic在 SQL 中连接多个表并执行算术运算
【发布时间】:2014-10-06 00:39:35
【问题描述】:

我需要有关 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

此查询遍历并计算疾病哮喘在疾病表中出现的次数,并将其与另一个名为 interview 的表链接,该表包含城市。它计算每个城市发生哮喘的次数。

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

查询:

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 限制了人口。

感谢大家的帮助!

【问题讨论】:

  • 从您的问题中不清楚您为什么指定 interview.dateOfInterview = 2012 但不只想要 2012 结果。你为什么不能把它放在外面? (另外,结果中的列名与查询不匹配,这令人困惑)。
  • @turophile 抱歉,这个问题是针对我需要显示 2012 年疾病 asmtha 的结果的问题。我在发帖时更改了名称,但我会对其进行编辑以清除它。
  • 在查询 1 中计算疾病,然后在查询 2 中计算访谈(乘以 200 得出人口)但是当您合并这两个表时,count(*) 将是合并后的结果,不再是任一表中的数字。
  • @turophile 最后我想要一个结果,这样我就可以划分疾病发生率/小地方,例如 2/400,然后乘以 100 得出患病率百分比
  • @turophile 数据库表样本:疾病:i57.tinypic.com/qn1fg6.png 采访:i60.tinypic.com/4smrk9.png 我已经创建了我的表的一些屏幕截图

标签: mysql sql database


【解决方案1】:

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

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;

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2022-06-14
  • 2014-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-03
  • 2014-02-06
相关资源
最近更新 更多