简体   繁体   中英

How to count distinct values over all rows 2 columns

I have 2 columns,and I am looking for a count of all distinct values in BOTH columns overall, not just the same row in both columns. IE here the count of distinct values is 9 because 1000, 5000, 7000 and 8000 will only be included once.

 x          y
 1000    NULL
 2000    1000
 3000    1000
 4000    1000
 5000    1000
 6000    5000
 7000    5000
 8000    7000
 9000    8000

You can unpivot the data and count:

select count(distinct x)
from ((select x from t) union all
      (select y from t)
     ) t;

That said, it looks like the first column is unique and has the information you want, so perhaps you simply want:

select count(*)
from t;

Or:

select count(distinct x)
from t;

Union is the way to go

    Select count(*) from(Select x from 
    table tx 
   union
   Select y from table ty) ;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM