天天看點

oracle distinct的用法,oracle中distinct的用法詳解

下面先來看看例子:

table表

字段1     字段2    id        name    1           a    2           b    3           c    4           c    5           b

庫結構大概這樣,這隻是一個簡單的例子,實際情況會複雜得多。

比如我想用一條語句查詢得到name不重複的所有資料,那就必須使用distinct去掉多餘的重複記錄。

select distinct name from table 得到的結果是:

----------

name    a    b    c

好像達到效果了,可是,我想要得到的是id值呢?改一下查詢語句吧:

select distinct name, id from table

結果會是:

----------

id name    1 a    2 b    3 c    4 c    5 b

distinct怎麼沒起作用?作用是起了的,不過他同時作用了兩個字段,也就是必須得id與name都相同的才會被排除。。。。。。。

我們再改改查詢語句:

select id, distinct name from table

很遺憾,除了錯誤資訊你什麼也得不到,distinct必須放在開頭。難到不能把distinct放到where條件裡?能,照樣報錯。

------------------------------------------------------------------------------------------------------------

下面方法也不可行:

select *, count(distinct name) from table group by name

結果:

ORA-00979: not a GROUP BY expression

00979. 00000 - "not a GROUP BY expression"

依然報錯,

group by 必須放在 order by 和 limit之前,不然會報錯

------------------------------------------------------------------------------------------------------------

偶認為這樣可行

select max(id), name from table group by name;

結果:

id name

1  a

2  b

4  c

5  d

用法二:

一、資料:

1    zjx    001    AAAiBZAAQAAAAVPAAA

2    zjx    002    AAAiBZAAQAAAAVPAAB

3    zjx    001    AAAiBZAAQAAAAVPAAC

二、多字段

select distinct t.name,t.code from test1 t

select distinct t.* from test1 t

結果:

1    zjx    001

2    zjx    002

三、單字段

select distinct t.name from test1 t

結果:

1    zjx