Wednesday, December 5, 2007

How to select count distinct number of two columns in SQL?

Note count (distinct column1, column2) is invalid.

You could use self join like this:

SELECT count(*) FROM table a FULL JOIN table b ON (a.column1 = b.column1 AND a.column2 = b.column2);

You could use sub query like this:

SELECT count(*) FROM ( SELECT 1 FROM table GROUP BY column1, column 2 ) zz ;
zz is the alias for sub-SELECT

You could use || like this:

SELECT count(distinct column1||'%'||column2 ) FROM table;

Maybe should use " instead of ' in some machine. And you also could use other words other than % to avoid mistakes.

No comments: