如何从本《守则》中按性别或身体状况按省获取男女总数?
SELECT sv.province_name, sv.district_name,
sum(sexual_female_less_10) as sexual_female_less_10,
sum(sexual_female_10_14) as sexual_female_10_14,
sum(sexual_female_15_19) as sexual_female_15_19,
sum(sexual_female_20_24) as sexual_female_20_24,
sum(sexual_female_25_plus) as sexual_female_25_plus,
sum(sexual_male_less_10) as sexual_male_less_10,
sum(sexual_male_10_14) as sexual_male_10_14,
sum(sexual_male_15_19) as sexual_male_15_19,
sum(sexual_male_20_24) as sexual_male_20_24,
sum(sexual_male_25_plus) as sexual_male_25_plus,
sum(physical_female_less_10) as physical_female_less_10,
sum(physical_female_10_14) as physical_female_10_14,
sum(physical_female_15_19) as physical_female_15_19,
sum(physical_female_20_24) as physical_female_20_24,
sum(physical_female_25_plus) as physical_female_25_plus,
sum(physical_male_less_10) as physical_male_less_10,
sum(physical_male_10_14) as physical_male_10_14,
sum(physical_male_15_19) as physical_male_15_19,
sum(physical_male_20_24) as physical_male_20_24,
sum(physical_male_25_plus) as physical_male_25_plus
FROM vw_experiencedphysicalviolence pv
JOIN vw_experiencedsexualviolence sv ON pv.id = sv.id
GROUP BY sv.district_name, sv.province_name
答案 0 :(得分:1)
一些细节。
GROUP BY
子句中,您将按地区和省进行分组。在您的问题中,指定省。如果正确的话,您的分组依据应该像这样GROUP BY sv.province_name
请参见下面的示例代码:
SELECT
sv.province_name,
sv.district_name, -- Remove if you remove from group by clause
sum(sexual_female_less_10) +
sum(sexual_female_10_14) +,
sum(sexual_female_15_19) +
sum(sexual_female_20_24) +
sum(sexual_female_25_plus) AS total_f_sexual_violence,
sum(physical_female_less_10) +
sum(physical_female_10_14) +
sum(physical_female_15_19) +
sum(physical_female_20_24) +
sum(physical_female_25_plus) AS total_f_physical_violence,
sum(sexual_male_less_10) +
sum(sexual_male_10_14) +
sum(sexual_male_15_19) +
sum(sexual_male_20_24) +
sum(sexual_male_25_plus) AS total_m_sexual_violence,
sum(physical_male_less_10) +
sum(physical_male_10_14) +
sum(physical_male_15_19) +
sum(physical_male_20_24) +
sum(physical_male_25_plus) AS total_f_physical_violence
FROM vw_experiencedphysicalviolence pv
JOIN vw_experiencedsexualviolence sv ON pv.id = sv.id
GROUP BY
sv.district_name, -- Per your question you may not want to group by district_name
sv.province_name
答案 1 :(得分:0)
您可以尝试使用OVER子句。
即:
SELECT DISTINCT
sv.province_name,
sv.district_name,
sum(sexual_female_less_10) OVER (partition by sv.province_name, sv.district_name) as District_sexual_female_less_10,
sum(sexual_female_less_10) OVER (partition by sv.province_name) as Province_sexual_female_less_10,
...
FROM vw_experiencedphysicalviolence pv
JOIN vw_experiencedsexualviolence sv ON pv.id = sv.id
有关更多信息:https://docs.microsoft.com/en-us/sql/t-sql/functions/sum-transact-sql?view=sql-server-2017