2012-05-14 27 views
3
SELECT DISTINCT col1, col2 FROM table t ORDER BY col1; 

這給了我不同的組合col1 & col2。是否有另外一種方法來編寫Oracle SQL查詢來獲得col1 & col2記錄與使用關鍵字distinct的唯一組合?SQL查詢模擬不同

+6

是它的功課?這讓我想起了一些我不得不做的學校工作:) – sp00m

回答

5

我不明白爲什麼你會想,但你可以做

SELECT col1, col2 FROM table_t GROUP BY col1, col2 ORDER BY col1 
+0

嗯這對我來說真的很像家庭作業。 – user1384586

+0

對於錯誤的評論感到抱歉。我也想避免組合。 – 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 
+0

編輯了'UNION'答案,'order by'應該在最後。 –

+0

而且,第三個答案在子查詢中根本不應該有'order by'。 –

+0

@ypercube謝謝! –

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 
+0

不應該'ORDER BY'在外部查詢,也(或只有)? –

+0

感謝這個查詢執行的響應速度比所有其他選項快。 – user1384586

+0

@ypercube:你說得對。它也應該在外面。它在內部是需要的,否則row_number()並不真正做出敏感 - 儘管它實際上可能沒有。但是大家都知道:除非指定'order by',否則不要依賴任何訂單。 –

6

運用獨特的關鍵字這是DISTINCT的同義詞:

SELECT UNIQUE col1, col2 FROM table t ORDER BY col1; 
+1

很好的回答:) –

+0

ahahah擁有:) –

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

上的變化@aF提供的UNION解決方案。 :

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;