如何根据一列distict值过滤结果集并使用oracle丢弃休息

时间:2016-09-20 09:21:58

标签: oracle

我有一个查询返回包含多个列的唯一记录集。即使整行是唯一的,列也可以有重复。我想只保留由某些列的不同值组成的行,并丢弃其余的行。什么是最好的方法

示例数据集:

col1    col2    col3    col4
10      Red     Book1   Large
30      Red     Book2   Medium

期望的结果

'A' - only matches attribute name
'E' - only matches element name
'C' - only matches class name
'M' - only matches comment

以上示例我保持col3不同并随机丢弃休息。

1 个答案:

答案 0 :(得分:2)

这适用于您的示例:

with test (col1, col2, col3, col4) as
(
  select 10, 'Red', 'Book1', 'Large'  from dual union all
  select 10, 'Blue','Book1', 'Small'  from dual union all
  select 20, 'Blue','Book1', 'Small'  from dual union all
  select 30, 'Red', 'Book2', 'Medium' from dual union all
  select 30, 'Blue','Book2', 'Small'  from dual
)
select col1, col2, col3, col4
from (
        select col1, col2, col3, col4,
               row_number() over ( partition by col3 order by col2 desc) countCol3
        from test
     )     
where countCol3 = 1

在这里,我决定保留,如果多行有col3的相同值,则最小值为col2的行;这只是为了适合您的示例,因此您应该编辑订购部分以更好地满足您的需求。

相关问题