巧用row_number() over()函式,選取重複記錄中想要的值

pwz1688發表於2009-04-01

剛在論壇看到一個貼子,感覺不錯,就拿來測試了下,呵~~

[@more@]

貼子內容

如何從某欄位重複的多條記錄條件查詢

求一個SQL語句寫法。

現有以問題,表資料如下:

A B C
1 a x
1 a y
1 a z
2 a x
2 a z
3 a x


需要查詢結果:如果A欄位存在相同值,且重複記錄中C欄位存在值為y的記錄,只取C欄位值為Y的記錄,如果重複記錄不存在C欄位為Y的記錄,任取一條A欄位重複的記錄。
如上表所需查詢結果為:

A B C 或者 A B C
1 a y 1 a y
2 a x 2 a z
3 a x 3 a x

下面是解答方法:
SQL> edit;
已寫入 file afiedt.buf
1 create table t as
2 ( select 1 as a, 'a' as b, 'x' as c from dual union all
3 select 1 as a, 'a' as b, 'y' as c from dual union all
4 select 1 as a, 'a' as b, 'z' as c from dual union all
5 select 2 as a, 'a' as b, 'x' as c from dual union all
6 select 2 as a, 'a' as b, 'z' as c from dual union all
7* select 3 as a, 'a' as b, 'x' as c from dual )
8 ;
表已建立。
SQL> select a,b,c from
2 (select a,b,c,row_number()over(partition by a order by decode(c,'y',1,2),c) rn
3 from t)
4 where rn=1;
A B C
---------- - -
1 a y
2 a x
3 a x
附:詳細分析下面sql結果
SQL> select t.*,decode(c,'y',1,2) from t;
A B C DECODE(C,'Y',1,2)
---------- - - -----------------
1 a x 2
1 a y 1
1 a z 2
2 a x 2
2 a z 2
3 a x 2
已選擇6行。
通過order by decode(c,'y',1,2),c 這二例,巧妙將分組後c為Y的值置為最前面.

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/21251711/viewspace-1019731/,如需轉載,請註明出處,否則將追究法律責任。

相關文章