Login or Sign Up to become a member!

EXPERTS, INFORMATION, IDEAS & KNOWLEDGE

Social bookmarker Add this

Your profile

Search

November 2008
Mon Tue Wed Thu Fri Sat Sun
 << <   > >>
          1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30

XML Feeds

« SQL Server 2008 cannot be installed if you have Visual Studio 2008 RTM installedHow Are Dates Stored In SQL Server? »
The Data Management Journal

Getting The Percentage Of NULLS And Values In A SQL Server Table

by SQLDenis


Permalink 05 Aug 2008 08:09 , Categories: Data Modelling & Design Tags: database, math, null, sql, sqlserver

Sometimes you want to know what the percentage is of null values in a table for a Column
Or you might want to know what the percentage of all values in a Column is grouped by value
You can get these answers by running the code below

First create this table

  1. CREATE TABLE #perc ( Column1 INT,Column2 INT,Column3 INT)
  2. INSERT INTO #perc
  3. SELECT NULL,1,1
  4. UNION ALL
  5. SELECT 1,1,1
  6. UNION ALL
  7. SELECT NULL,NULL,1
  8. UNION ALL
  9. SELECT NULL,1,NULL
  10. UNION ALL
  11. SELECT NULL,1,1
  12. UNION ALL
  13. SELECT 1,1,NULL
  14. UNION ALL
  15. SELECT NULL,1,1
  16. UNION ALL
  17. SELECT 2,1,2
  18. UNION ALL
  19. SELECT 3,1,1

Get the percentage of nulls in all the Columns in my table

  1. SELECT 100.0 * SUM(CASE WHEN Column1 IS NULL THEN 1 ELSE 0 END) / COUNT(*) AS Column1Percent,
  2. 100.0 * SUM(CASE WHEN Column2 IS NULL THEN 1 ELSE 0 END) / COUNT(*) AS Column2Percent,
  3. 100.0 * SUM(CASE WHEN Column3 IS NULL THEN 1 ELSE 0 END) / COUNT(*) AS Column3Percent
  4. FROM #perc

Output

Column1Percent	Column2Percent	Column3Percent
55.555555555555	11.111111111111	22.222222222222

Get the values and the percentage of all values for a Column

  1. SELECT Column3 AS VALUE,COUNT(*) AS ValueCount,
  2. 100.0 * COUNT(COALESCE(Column3,0))/(SELECT COUNT(*) FROM #perc ) AS Percentage
  3. FROM #perc
  4. GROUP BY Column3
  5. ORDER BY Percentage DESC

Output

Value	ValueCount	Percentage
1	6	66.666666666666
NULL	2	22.222222222222
2	1	11.111111111111
Leave a comment »Send a trackback » 656 views

Trackback address for this post

Trackback URL (right click and copy shortcut/link location)

No feedback yet

Leave a comment


Your email address will not be revealed on this site.

Your URL will be displayed.
PoorExcellent
(Line breaks become <br />)
(Name, email & website)
(Allow users to contact you through a message form (your email will not be revealed.)