SQL:出现次数仅占某些值的百分比

SQL: Number of occurrences as a percentage of only certain values

我正在尝试查看位于农村或城市的组织的比例 - 'Rurality' 类别有 'Rural'、'Urban' 或 'NULL' .我可以计算 'Urban' 和 'Rural' 占所有值的百分比,但我想排除所有出现 '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' 和 'Rural' 达到我的 100%,不包括 'NULL' 值。

如果有任何不同,我正在使用 SSMS。

在您的子查询中,您必须像这样在 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

您可以简单地切换到 COUNT(Geography_Rurality_DEFRA_Grouped) 而不是 COUNT(*),这将排除 NULL。

但是SQL服务器支持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