模拟去重的SQL查询

3
SELECT DISTINCT col1, col2 FROM table t ORDER BY col1;

这给了我col1col2的独特组合。是否有其他方法编写Oracle SQL查询以获取col1col2记录的唯一组合,而不使用关键字distinct?


6
是作业吗?这让我想起了我曾经要做的一些学校作业 :) - sp00m
7个回答

6
使用UNIQUE关键字,它是DISTINCT的同义词:
SELECT UNIQUE col1, col2 FROM table t ORDER BY col1;

5
我不明白你为什么想要这样做,但是你可以这样做。
SELECT col1, col2 FROM table_t GROUP BY col1, col2 ORDER BY col1

抱歉之前的评论有误,我也想避免使用 group by。 - user1384586

3
select col1, col2
from table
group by col1, col2
order by col1

或者一种不太优雅的方式:
select col1,col2 from table
UNION
select col1,col2 from table
order by col1;

或者更不太优雅的方法:
select a.col1, a.col2
from (select col1, col2 from table
UNION
select NULL, NULL) a
where a.col1 is not null
order by a.col1

而且,第三个答案在子查询中根本不应该有 order by - ypercubeᵀᴹ
Union很聪明,因为UNION默认具有DISTINCT,而SELECT则默认具有ALL操作。 - ypercubeᵀᴹ
@ypercube 是的,但是按组排序似乎更优雅 ^^ - aF.

3
另一个解决方案 - 过于复杂且有些无用的 - 是:
select *
from (
   select col1, 
          col2, 
          row_number() over (partition by col1, col2 order by col1, col2) as rn
   from the_table
)
where rn = 1
order by col1

ORDER BY 应该也在外部查询中吗?或者只在那里? - ypercubeᵀᴹ
感谢您的回复,此查询比其他选项执行得更快。 - user1384586
@ypercube:你是对的。它也应该在外部。如果不在内部,row_number()就没有意义了 - 尽管它可能实际上可以正常工作。但正如我们所知道的那样:永远不要依赖任何顺序,除非指定了“order by”。 - user330315

3

又一个...

select
  col1,
  col2
from
  table t1
where
  not exists (select *
                from table t2
               where t2.col1  = t1.col1 and
                     t2.col2  = t1.col2 and
                     t2.rowid > t1.rowid)
order by
  col1;

2
变体UNION解决方案由@aF提供: INTERSECT
SELECT col1, col2 FROM tableX
INTERSECT
SELECT col1, col2 FROM tableX
ORDER BY col1;

MINUS

SELECT col1, col2 FROM tableX
MINUS
SELECT col1, col2 FROM tableX WHERE 0 = 1
ORDER BY col1;

MINUS(第二个版本,如果存在(NULL, NULL)分组,则返回的行数比其他版本少一行)

SELECT col1, col2 FROM tableX
MINUS
SELECT NULL, NULL FROM dual
ORDER BY col1;

1

另一个...

select   col1,
         col2
from     (
         select col1,
                col2,
                rowid,
                min(rowid) over (partition by col1, col2) min_rowid
         from   table)
where    rowid = min_rowid
order by col1;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接