27 Şubat 2013 Çarşamba

Oracle sql with kullanımı


Oracle sql with kullanımı
With kullanımı Prosedürlerdeki cursor gibi düşünebiliriz.
Bir örnek üzerinde gerçekleştirelim.
Öğrenci tablosu (OGRENCI)
OGRENCI_ID     OGRENCI_ADI
1                            Ahmet
2                            Ayşe
3                            Hasan


Ders tablosu (DERS)
DERS_ID              DERS_ADI
1                            Matematik
2                            Tarih
3                            Türkçe


Bir dersi alan Öğrenci tablosu (OGRENC_DERS)
DERS_ID              OGRENCI_ID
1                                     1
1                                     2
1                                     3
2                                     1
2                                     3
3                                     2
3                                     3


Ders alan öğrencilerin sql’ini yazalım.
Select  od.OGRENCI_ID,d.DERS_ADI, d. DERS_ID
From  OGRENCI_DERS od ,DERS d
Where  od.DERS_ID=d.DERS_ID


Öğrenci numaralarıyla ders isimlerini listeledik. Bizim buradaki isteğimiz  bir öğrenciye ait ders bilgilerini alt alta getirmek yerine yan yana getirmeyi sağlamak olacaktır. Yukarıdaki sql cümleciğini with aralığına alacağız.

Son sql hali

With tablo as
(
Select  od.OGRENCI_ID,d.DERS_ADI,d. DERS_ID
From  OGRENCI_DERS od ,DERS d
Where  od.DERS_ID=d.DERS_ID
)
Select  o.OGRENCI_ADI,
(select t.DERS_ADI from tablo t where tablo t. OGRENCI_ID=o. OGRENCI_ID and o.DERS_ID =1)  as DERS1,
(select t.DERS_ADI from tablo t where tablo t. OGRENCI_ID=o. OGRENCI_ID and o.DERS_ID =2)  as DERS2,
(select t.DERS_ADI from tablo t where tablo t. OGRENCI_ID=o. OGRENCI_ID and o.DERS_ID =3)  as DERS3,
From OGRENCI o

Sql Sonucu

OGRENCI_ADI       DERS1                    DERS2                    DERS3
AHMET                  MATEMATİK         TARİH                     NULL
AYŞE                       MATEMATİK         NULL                      TÜRKÇE
HASAN                   MATEMATİK         TARİH                     TÜRKÇE

3 yorum: