我是复杂 SQL 语句的新手,需要帮助。我已经设法显示了一半的结果集并努力剩余。
所需结果:
PSU | pregnancy number| pregnancy percentage | % of live birth out of the pregnancy number.
1 | 2 | 67% | 40%
2 | 1 | 33% | 80%
使用下面编写的 sql,我设法获得了前 3 列。
第 2 列和第 3 列需要 where 语句fieldname = 'Q111'
。而第 4 列需要带有 where 语句的百分比fieldname = 'Q112
。如何将不同的 where 语句组合在一起。
SELECT sms_psu.name1 AS PSU,
woman_data.answertext AS NumberOfPreg,
Count(woman_data.answertext) / (SELECT Count(woman_data.answertext)
FROM woman_data
INNER JOIN sms_household
ON woman_data.prim_key =
ms_household.hhid
INNER JOIN sms_psu
ON sms_psu.psu =
sms_household.psu
WHERE sms_psu.state = 19
AND sms_psu.district = 1
AND sms_psu.psu = 2
AND fieldname = 'Q139') AS
totalcpuntpreg
FROM woman_data
INNER JOIN sms_household
ON woman_data.prim_key = sms_household.hhid
INNER JOIN sms_psu
ON sms_psu.psu = sms_household.psu
WHERE sms_psu.state = 19
AND sms_psu.district = 1
AND sms_psu.psu = 2
AND fieldname = 'Q111'
GROUP BY woman_data.answertext,
sms_household.psu
戈登,你的建议对我帮助很大。我相应地更新了我的查询。我现在写的问题是我为 Q112 增加了一行
电源 | 妊娠数| 怀孕百分比| 妊娠数中活产的百分比。
1 | 2 | 67% | 40%
2 | 1 | 33% | 80%
2 | 1 | 0% | 20%(第 112 季度的第三行是额外的)
但是我在分组时不需要 Q112 条目。我可以在 case 语句和 main where 语句中分别使用 group by 吗?我尝试将“有”与 group by 一起使用,但得到了预期的结果。