Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Oracle 11g SQL to get unique values in one column of a multi-column query

Given a table A of people, their native language, and other columns C3 .. C10 represented by ...

Table A

 PERSON   LANGUAGE   ... bob      english john     english vlad     russian olga     russian jose     spanish 

How do I construct a query which selects all columns of one row for each distinct language?

Desired Result

 PERSON   LANGUAGE   ... bob      english vlad     russian jose     spanish 

It doesn't matter to me which row of each distinct language makes the result. In the result above, I chose the lowest row number of each language.

like image 392
Ian Cohen Avatar asked Jun 11 '09 19:06

Ian Cohen


People also ask

How can I get distinct values of two columns in SQL?

To select distinct values in two columns, you can use least() and greatest() function from MySQL.

Can I use distinct with multiple columns?

Answer. Yes, the DISTINCT clause can be applied to any valid SELECT query. It is important to note that DISTINCT will filter out all rows that are not unique in terms of all selected columns.

How can I get unique values from a column with repeated values in SQL?

The SQL SELECT DISTINCT Statement The SELECT DISTINCT statement is used to return only distinct (different) values. Inside a table, a column often contains many duplicate values; and sometimes you only want to list the different (distinct) values.

How can I get distinct values of all columns in SQL?

To get unique or distinct values of a column in MySQL Table, use the following SQL Query. SELECT DISTINCT(column_name) FROM your_table_name; You can select distinct values for one or more columns.


2 Answers

Eric Petroelje almost has it right:

SELECT * FROM TableA WHERE ROWID IN ( SELECT MAX(ROWID) FROM TableA GROUP BY Language ) 

Note: using ROWID (row unique id), not ROWNUM (which gives the row number within the result set)

like image 174
Joe Avatar answered Sep 28 '22 12:09

Joe


This will be more efficient, plus you have control over the ordering it uses to pick a value:

SELECT DISTINCT        FIRST_VALUE(person)           OVER(PARTITION BY language                ORDER BY person)       ,language FROM   tableA; 

If you really don't care which person is picked for each language, you can omit the ORDER BY clause:

SELECT DISTINCT        FIRST_VALUE(person)           OVER(PARTITION BY language)       ,language FROM   tableA; 
like image 33
Jeffrey Kemp Avatar answered Sep 28 '22 12:09

Jeffrey Kemp