Thanks for the question, Raghavendra.
Asked: December 02, 2014 - 1:01 pm UTC
Last updated: December 03, 2014 - 3:37 pm UTC
Version: 11.2
Viewed 10K+ times! This question is
You Asked
CREATE TABLE country_test (c1 varchar2(20), c2 varchar2(20), c3 varchar2(20),c4 varchar2(20))
/
INSERT INTO country_test VALUES ('india','us','china','uk')
/
INSERT INTO country_test VALUES ('india','india','china','uk')
/
INSERT INTO country_test VALUES ('india','china','china','uk')
/
INSERT INTO country_test VALUES ('us','us','us','uk')
/
commit;
select * from country_test
/
c1 c2 c3 c4
--------------------------
india us china uk
india india china uk
india china china uk
us us us uk
I Need the distinct count of countries across columns of the table i.e distinct across c1,c2,c3,c4. So the output has to be
c1 c2 c3 c4 cnt
-----------------------------------
india us china uk 4
india india china uk 3
india china china uk 3
us us us uk 2
If possible, Can the query be made generic to support any number of combinations
of the columns and give the distinct count across all the columns?
Thanks a Ton for your support!.
Regards,
Boralli
and Tom said...
it really won't be "generic" in that if you have 4 columns, you'll need to reference 4 columns. If you have 5, you'll need a different query.
this query works by generating a set of four rows (data), then doing a cartesian join of that to the original table turning each single row into four duplicates. Using decode, we populate a single column in each of those rows - one of the four original columns. We keep the primary key (rowid in this case) so we can group by safely (in case two rows have the same c1..c4 values).
ops$tkyte%ORA11GR2> with data(r)
2 as
3 (select 1 r from dual
4 union all
5 select r+1 from data where r < 4
6 )
7 select c1, c2, c3, c4, count(distinct c) cnt
8 from (
9 select rowid rid,
10 c1, c2, c3, c4,
11 decode(r,1,c1,2,c2,3,c3,4,c4) c
12 from data, country_test
13 )
14 group by rid, c1, c2, c3, c4
15 /
C1 C2 C3 C4 CNT
---------- ---------- ---------- ---------- ----------
india us china uk 4
us us us uk 2
india india china uk 3
india china china uk 3
Rating
(9 ratings)
Is this answer out of date? If it is, please let us know via a Comment