我试图了解位于农村或城市地区的组织的比例 - 类别'乡村性'有乡村' Urban' Urban'或者' NULL'。我可以计算出城市'的百分比。和乡村'作为所有值的百分比,但我想要排除所有出现的' NULL'值。
目前我有:
SELECT Geography_Rurality_DEFRA_Grouped as 'Type',
COUNT(*) as 'Count',
(COUNT(Geography_Rurality_DEFRA_Grouped)* 100 / (SELECT COUNT(*) FROM [SWFC_Project].[dbo].[Lookup_SchoolLevelIndicators])) AS Perc
FROM [SWFC_Project].[dbo].[Lookup_SchoolLevelIndicators]
WHERE Geography_Rurality_DEFRA_Grouped IS NOT NULL
GROUP BY [Geography_Rurality_DEFRA_Grouped]
ORDER BY 'Count' desc, Geography_Rurality_DEFRA_Grouped
我的输出是:
Type | Count | Perc
-------------------
Urban| 78117 | 72
Rural| 27693 | 25
然而,百分比只增加了97%,而我想要' Urban'和乡村'到我的100%,排除' NULL'值。
如果有任何不同,我会使用SSMS。
答案 0 :(得分:2)
在子查询中,您必须在IS NOT NULL上添加条件,如下所示:
SELECT Geography_Rurality_DEFRA_Grouped as 'Type',
COUNT(*) as 'Count',
(COUNT(Geography_Rurality_DEFRA_Grouped)* 100 /
(SELECT COUNT(*)
FROM [SWFC_Project].[dbo].[Lookup_SchoolLevelIndicators]
WHERE Geography_Rurality_DEFRA_Grouped IS NOT NULL) AS Perc
FROM [SWFC_Project].[dbo].[Lookup_SchoolLevelIndicators]
WHERE Geography_Rurality_DEFRA_Grouped IS NOT NULL
GROUP BY [Geography_Rurality_DEFRA_Grouped]
ORDER BY 'Count' desc, Geography_Rurality_DEFRA_Grouped
答案 1 :(得分:1)
您只需切换到COUNT(Geography_Rurality_DEFRA_Grouped)
而不是COUNT(*)
,这会排除NULL。
但是SQL Server支持Windowed Aggregate Function,你只需要一个 GROUP SUM :
SELECT Geography_Rurality_DEFRA_Grouped AS 'Type',
COUNT(Geography_Rurality_DEFRA_Grouped) AS 'Count',
100 * COUNT(*) / SUM(COUNT(*)) OVER () AS Perc
FROM [SWFC_Project].[dbo].[Lookup_SchoolLevelIndicators]
WHERE Geography_Rurality_DEFRA_Grouped IS NOT NULL
GROUP BY [Geography_Rurality_DEFRA_Grouped]
ORDER BY 'Count' DESC, Geography_Rurality_DEFRA_Grouped