0

I have a table with column1 and column2 among other columns?

I need a count of unique values across all rows taken from column1 and column2. Possible query: select count(*) from ( (select distinct column1 from table1) UNION (select distinct column2 from table1) );

I also need a count of unique values across all rows as per below :- "column1" + "-" + "column2" "column2" + "-" + "column1"

Possible query: select count(*) from ( (select distinct column1, column2 from table1) UNION (select distinct column2, column1 from table1) )

I think there is a possible flaw with both queries.

Sample Data :

Column 1 Column 2 Value1 null null Value1 Value1 Value2 Value2 Value1 Value4 null Value5 null

Result for Query 1 : 4 (Value1, Value2, Value4, Value5) Result for Query 2 : 5 (Value1, Value1-Value2, Value2-Value1, Value4, Value5)

Null is to be ignored with hyphen being excluded. Or hyphen can be ignored. Not particular about the hyphen.

Parag Ahire
  • 37
  • 1
  • 6

1 Answers1

0

Sounds like you need something similar to this

SELECT 
COUNT(DISTINCT [a])

FROM    
(SELECT Column1 [a]
FROM TableA
UNION ALL
SELECT Column2
FROM TableA 

) [x]
Simon
  • 496
  • 4
  • 19
  • 1
    Since the result must be de-duplicated in the end anyway, why not simply use `UNION` instead of `UNION ALL`? Then you won't need to count DISTINCT. –  Nov 29 '18 at 02:19