Sometimes you want to know what the percentage is of null values in a table for a field
Or you might want to know what the percentage of all values in a field is grouped by value
You can get these answers by running the code below
CREATE TABLE #perc ( Field1 INT,Field2 INT,Field3 INT)
INSERT INTO #perc
SELECT NULL,1,1
UNION ALL
SELECT 1,1,1
UNION ALL
SELECT NULL,NULL,1
UNION ALL
SELECT NULL,1,NULL
UNION ALL
SELECT NULL,1,1
UNION ALL
SELECT 1,1,NULL
UNION ALL
SELECT NULL,1,1
UNION ALL
SELECT 2,1,2
UNION ALL
SELECT 3,1,1
--Get the percentage of nulls in all the fields in my table
SELECT 100.0 * SUM(CASE WHEN Field1 IS NULL THEN 1 ELSE 0 END) / COUNT(*) AS Field1Percent,
100.0 * SUM(CASE WHEN Field2 IS NULL THEN 1 ELSE 0 END) / COUNT(*) AS Field2Percent,
100.0 * SUM(CASE WHEN Field3 IS NULL THEN 1 ELSE 0 END) / COUNT(*) AS Field3Percent
FROM #perc
--Get the values and the percentage of all values in a field
SELECT Field3 AS Value,COUNT(Field3) AS ValueCount,
100.0 * COUNT(coalesce(Field3,0))/(SELECT COUNT(*) FROM #perc ) AS Percentage
FROM #perc
GROUP BY Field3
ORDER BY Percentage DESC
DROP TABLE #perc
No comments:
Post a Comment