Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I select distinct count over multiple columns?

Tags:

mainframe

db2

How to select distinct count over multiple columns?

SELECT COUNT(DISTINCT col1, col2, col3) FROM table; 

Is there a working equivalent of this in DB2?

like image 757
Tonan Avatar asked Jan 09 '18 12:01

Tonan


People also ask

How can I get distinct values from multiple columns in SQL?

In SQL multiple fields may also be added with DISTINCT clause. DISTINCT will eliminate those rows where all the selected fields are identical.

How do I select all columns with distinct on one column?

SELECT DISTINCT FIELD1, FIELD2, FIELD3 FROM TABLE1 works if the values of all three columns are unique in the table. If, for example, you have multiple identical values for first name, but the last name and other information in the selected columns is different, the record will be included in the result set.

How do I select multiple columns in select query?

To select multiple columns from a table, simply separate the column names with commas! For example, this query selects two columns, name and birthdate , from the people table: SELECT name, birthdate FROM people; Sometimes, you may want to select all columns from a table.


2 Answers

There are multiple options:

select count(*) from
   (select distinct col1, col2, col3 FROM table) t

The other would be to combine the columns via a CONCAT:

select count(distinct col1 || col2 || col3) from table

The first option is the cleaner (and likely faster) one.

like image 97
data_henrik Avatar answered Nov 02 '22 11:11

data_henrik


select count(distinct col1 || '^' || col2 || '^' || col3) from table

to avoid problems during concatenation like between 1 || 11 which would be the same as 11 || 1.

like image 1
Burkhard Lau Avatar answered Nov 02 '22 09:11

Burkhard Lau