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

这给了我独特的col1&组合col2。是否有另一种编写 Oracle SQL 查询的方法来获得col1&col2记录的唯一组合,而不使用关键字 distinct?

4

7 回答 7

6

使用作为 DISTINCT 同义词的 UNIQUE 关键字:

SELECT UNIQUE col1, col2 FROM table t ORDER BY col1;
于 2012-05-14T12:28:12.573 回答
5

我不明白你为什么想要,但你可以做到

SELECT col1, col2 FROM table_t GROUP BY col1, col2 ORDER BY col1
于 2012-05-14T12:15:48.070 回答
3

Yet another ...

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;
于 2012-05-14T12:38:46.487 回答
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
于 2012-05-14T12:20:34.387 回答
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
于 2012-05-14T12:17:08.487 回答
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;
于 2012-05-14T12:43:26.653 回答
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;
于 2012-05-14T13:19:02.007 回答