Distinct函數(shù)的替代方法
?
?
??? 今天在論壇上看到一個面試題,是說有什么辦法可以替代distinct,得到同樣的結(jié)果。答案都被大家說的差不多了,發(fā)現(xiàn)挺有意思的,就記錄一下:
SQL> select num from t1;
?????? NUM
----------
???????? 6
???????? 6
???????? 7
???????? 8
???????? 9
???????? 1
???????? 1
???????? 1
?????? 1
??????? 1
???????? 1
???????? 1
???? ?? 1
??? ???? 1
??????? 1
15 rows selected
?
SQL> select distinct num from t1;
?????? NUM
----------
???????? 1
???????? 6
???????? 8
????? ? 7
??????? 9
5 rows selected
一、用unique代替distinct:
這個比較無恥,基本屬于說了跟沒說一樣,但確實是對的
SQL> select unique num from t1;
?????? NUM
----------
???????? 1
???????? 6
???????? 8
????? ? 7
??????? 9
5 rows selected
二、用group by來做:
這個應該是出題者的本意
SQL> select num from t1 group by num;
?????? NUM
----------
???????? 1
???????? 6
???????? 8
???????? 7
???????? 9
5 rows selected
三、用union和minus:
因為union和minus默認都是先distinct然后再做聚集,所以可以這樣做:
SQL> select num from t1 minus select 999 from dual;
?????? NUM
----------
???????? 1
???????? 6
???????? 7
???????? 8
???????? 9
5 rows selected
?
SQL> select num from t1 union select num from t1 ;
?????? NUM
----------
???????? 1
???????? 6
???????? 7
???????? 8
???????? 9
5 rows selected
一個是minus一個沒有的項,一個是union它本身。
關于其他的方法,要是再用over之類的就沒有什么太大的意義了,差不多就這3種了。
?
?
?