3

I need to write a statement to display every column in a table, the count and percentage of records with that column populated, and the distinct count of values.

For example if I had a table Address containing:

Addr1 | AddrText  | PostalCode
11111 | demo ave  | 91210
22222 | demo2 ave | null
33333 | null      | null

It should display something like:

columns    | Count | Percentage
Addr1      | 3     | 100
AddrText   | 2     | 66.6
PostalCode | 1     | 33.3

Or have the columns remain the same and put only the data as rows, but I figured the above may be easier.

ps: Sorry if I couldn't get the formatting right but I hope you get the idea.

Yusubov
  • 5,815
  • 9
  • 32
  • 69
user1985569
  • 183
  • 2
  • 8

2 Answers2

3

You can unpivot the columns using UNION ALL and then apply an aggregate function to get the count and percentage:

select col,
  count(case when col is not null and value is not null then 1 end) CntCol,
  (count(case when col is not null and value is not null 
         then 1 end) / count(col))*100.0 Percentage
from
(
  select 'Addr1' col, Addr1 value
  from yourtable
  union all 
  select 'AddrText' col, AddrText value
  from yourtable
  union all 
  select 'PostalCode' col, PostalCode value
  from yourtable
) src
group by col

See SQL Fiddle with Demo

The result is:

|        COL | CNTCOL | PERCENTAGE |
------------------------------------
|      Addr1 |      3 |        100 |
|   AddrText |      2 |   66.66667 |
| PostalCode |      1 |   33.33333 |
Taryn
  • 242,637
  • 56
  • 362
  • 405
0
SELECT 'Addr1' col, 
       COUNT(Addr1) cntcol, COUNT(addr1)/count(*) percentage
FROM yourtable
union all
SELECT 'AddrText' col, 
       COUNT(AddrText) cntcol, COUNT(AddrText)/count(*) percentage
FROM yourtable
union all
SELECT 'PostalCode' col, 
       COUNT(PostalCode) cntcol, COUNT(PostalCode)/count(*) percentage
FROM yourtable
Hogan
  • 69,564
  • 10
  • 76
  • 117