Skip to Main Content
  • Questions
  • How to get unique values/blanks across all columns

Breadcrumb

Question and Answer

Chris Saxon

Thanks for the question, Its.

Asked: October 10, 2019 - 2:13 pm UTC

Last updated: October 11, 2019 - 1:39 pm UTC

Version: 11

Viewed 10K+ times! This question is

You Asked

Hi,

I have a wide table with 200 odd columns. Requirement is to pivot the columns and display the unique values and count of blanks within each column

CREATE TABLE example(
c1 VARCHAR(10),
c2 VARCHAR(10),
c3 VARCHAR(10)
);
/
INSERT INTO example VALUES('abc', '123', 'speed');
INSERT INTO example VALUES('cat', 'crazy', 'no');
INSERT INTO example VALUES('dog', 'yes', 'no');
INSERT INTO example VALUES('dog', 'row', 'no');
INSERT INTO example VALUES(null,null,'no');
commit;
/


Result should be in the pivoted format as given below.

    unique    Countofblank 
    -----------------------
c1    4         1                      
c2    5         1                   
c3    2         0                


Could you please help ?

Thanks

and Chris said...

Rather than PIVOT, it sounds like you want to:

- UNPIVOT the columns
- Group by these to get the counts

Note count ( distinct ) excludes null values. From your output it looks like you want to include these in your distinct count. So you need to map NULL to some "impossible" value (e.g. the string "NULL").

To get the nulls you also need to map these to a non-null value. And the non-nulls to null :)

Which gives:

CREATE TABLE example(
  c1 VARCHAR(10),
  c2 VARCHAR(10),
  c3 VARCHAR(10)
);
/
INSERT INTO example VALUES('abc', '123', 'speed');
INSERT INTO example VALUES('cat', 'crazy', 'no');
INSERT INTO example VALUES('dog', 'yes', 'no');
INSERT INTO example VALUES('dog', 'row', 'no');
INSERT INTO example VALUES(null,null,'no');
commit;
/
with rws as (
  select * from example
  unpivot include nulls (
    val for col in ( 
      c1, c2, c3
    )
  )
)
  select col, 
         count ( distinct val ) distinct_vals,
         count ( distinct case when val is null then 'NULL' else val end ) distinct_vals_with_null,
         count ( case when val is null then 1 end ) nulls
  from   rws
  group  by col;

CO DISTINCT_VALS DISTINCT_VALS_WITH_NULL      NULLS
-- ------------- ----------------------- ----------
C1             3                       4          1
C2             4                       5          1
C3             2                       2          0


Is this answer out of date? If it is, please let us know via a Comment

More to Explore

SQL

The Oracle documentation contains a complete SQL reference.