SQL如果组遵循某些规则,如何查找多个组的平均值

问题描述 投票:0回答:2

这是我目前的代码:

SELECT
AVG(famTotal)

FROM `OmniHealth.new2015Data`, (
SELECT
SUM( TOTEXP15 ) as famTotal
FROM `OmniHealth.new2015Data` 

GROUP BY DUID
)
WHERE BMINDX53 BETWEEN 0 AND 25 AND
ADSMOK42 = -1 AND
FCSZ1231 = 7

我想要做的是找到每个家庭的平均成本,其家庭所有成员的BMI在0到25之间,不吸烟,家庭是任意大小。

支出数据在表格中以人为单位,所以我试图根据所有人的“住宅单位ID”(DUID)进行求和,然后平均每个家庭的总数。因为这个家庭只有我在最后一段中陈述的财产。

感谢您的答复!我是SQL的新手。

sql google-bigquery bigdata
2个回答
1
投票

考虑加入两个与计数匹配的聚合查询派生表,以使所有家庭成员与具有特定条件的所有家庭成员对齐。

SELECT AVG(t1.famTotal) as famTotal

FROM
  (SELECT DUID, Count(*) As GrpCount, SUM(TOTEXP15) as famTotal
   FROM `OmniHealth.new2015Data` 
   GROUP BY DUID) As t1

INNER JOIN

  (SELECT DUID, Count(*) As GrpCount
   FROM `OmniHealth.new2015Data` 
   WHERE BMINDX53 BETWEEN 0 AND 25 
     AND ADSMOK42 = -1 
     AND FCSZ1231 = 7
   GROUP BY DUID) As t2

ON t1.DUID = t2.DUID AND t1.GrpCount = t2.GrpCount

1
投票

以下是BigQuery Standard SQL

#standardSQL
SELECT DUID, AVG(TOTEXP15) AS famAverage
FROM `OmniHealth.new2015Data` 
GROUP BY DUID
HAVING MIN(BMINDX53) >=0 AND MAX(BMINDX53) <=25
AND MIN(ADSMOK42) = -1 AND MAX(ADSMOK42) = -1
AND MIN(FCSZ1231) = 7 AND MAX(FCSZ1231) = 7
© www.soinside.com 2019 - 2024. All rights reserved.