如何基于选定的列而不是Oracle中表的所有列获取不同的行

时间:2019-02-13 11:37:48

标签: oracle

我试图获取前三列,而最后一列可以具有任何值。如果我在所有列上都做得不同,那么它将给我8行。该表是动态的,因此我将需要不同的3列以及最后一列中的任何值。

我有以下场景,

Name       Surname   Road           Pet
John       Trav     John_road       dog
Kaley      Couco    Couco_road     horse
Charlie    Sheen    Sheen_road     rabbit 
Johnny     Galecki  Galecki_road    cat 
John       Trav     John_road      donkie
Kaley      Couco    Couco_road      mouse
Charlie    Sheen    Sheen_road      goat
Johnny     Galecki  Galecki_road    pig

所需结果:

Name       Surname   Road           Pet
John       Trav     John_road       dog
Kaley      Couco    Couco_road     mouse
Charlie    Sheen    Sheen_road     rabbit 
Johnny     Galecki  Galecki_road    cat 

我尝试了此链接上的解决方案,但是它不起作用:

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

请在Oracle中提供帮助

3 个答案:

答案 0 :(得分:2)

由于您不在乎最后一列的值,一个简单的选择是将其汇总为

select name, surname, road, max(pet) 
from your_table
group by name, surname, road

答案 1 :(得分:0)

在前三列中将row_number()partition by一起使用:

dbfiddle demo

select * 
  from (
    select t.*, 
           row_number() over (partition by Name, Surname, Road order by pet) rn 
      from t)
  where rn = 1

答案 2 :(得分:0)

您尝试过

SELECT NAME, SURNAME, rOAD, PET FROM 
(
SELECT NAME, SURNAME, rOAD, PET, ROW_NUMBER () OVER (PARTITION BY NAME, SURNAME, rOAD ORDER BY PET) RN FROM FROM TABLE_NAME
) WHERE RN=1