简体   繁体   中英

ORACLE Select Distinct return many columns and where

I have a table which looks like this:

NAME    Col1     Col2    Col3
Tim     1        2       3
Tim     1        1       2
Tim     2        1       2
Dan     1        2       3
Dan     2        2       1
Dan     2        1       3

Im trying to make a SELECT command which results in this:

NAME    Col1     Col2    Col3
Tim     2        1       2
Dan     2        2       1

So I want distinct Names but select all four columns and where Col1 = 2. I used the solution here to get the distinct part working: SQL/mysql - Select distinct/UNIQUE but return all columns?

But when I add add Col1 = '2' to the WHERE part of the select statement is does not return all names where Col1 is 2 because i think it looks at a different one first which is not 1 so takes that result.

Hope I made sense and someone can help. Was hard to explain and come up with a good title. Thanks!

If selecting just those 2 columns (name and col1) is sufficent you can use:

select 
    distinct x.name, x.col1
  from table_name x
  where x.col1 = 2;

or

select 
    x.name, x.col1
  from table_name x
  where x.col1 = 2
  group by (x.name, x.col1);  

In case you need all values but you dont mind which one for the multiple records fulfilling your criteria yu get (eg Dan 2 2 1 or Dan 2 1 3), you can use this (it will record first of those records based on order by criteria):

select xx.name, xx.col1, xx.col2, xx.col3
  from (select 
      x.name, x.col1, x.col2, x.col3, dense_rank() over (partition by x.name order by x.name, x.col1, x.col2, x.col3) rnk
    from table_name x
    where x.col1 = 2) xx
  where xx.rnk = 1;

As I understand this query should solve your problem:

select distinct a.* from temp_ids a join

(select name, max(col1 || ' ' || col2  || ' ' || col3) id
from temp_ids
where col1 = 2
group by name
) b

on (a.name = b.name and (col1 || ' ' || col2  || ' ' || col3) = b.id)
;

Of cause, better to use unique record id instead concatenation, but generated id is possible. Be sure that function for id returns unique value for each combination of columns (in this case used (col1 || ' ' || col2 || ' ' || col3) )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM