Skip to Main Content

SQL & PL/SQL

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Self join on a table with condition to extract records

user555994Jul 4 2013 — edited Jul 4 2013

Hello PL/SQL Gurus/experts,

I am using Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - 64bit Production version
I have following table -

drop table t1;

create table t1(stud_NM,stud_id) as select

'Vikas',1 from dual union all select

'Andy',2 from dual union all select

'Chi',3 from dual union all select

'Derek',4 from dual union all select

'Kristien',5 from dual union all select

'Tom',6 from dual union all select 

'Messi',7 from dual union all select

'Ketty',8 from dual;

drop table t2;

create table t2(stud_id,Class, CDate) as select

1,'BA','20120101' from dual union all select

1,'MA','20120101' from dual union all select

2,'BSc','20120531' from dual union all select

3,'MCA','20120606' from dual union all select

4,'MCA','20120701' from dual union all select

4,'Btech','20120715' from dual union all select

5,'MTech','20120730' from dual union all select

6,'MSc','20120801' from dual union all select

6,'MSc','20120802' from dual union all select   

7,'MA','20120815' from dual union all select

8,'MA','20120815' from dual;

I have to get the output based on condition -

Extract Stud_Name, Count of records which has a condition as that of the one that if combination of Stud_Name & CDate is same then count this combination once only else if Stud_Name & CDate are different then count them as different records -

Currently i am using the following query to get the output -

select t1.stud_NM, count(distinct CASE WHEN orig.CDate<>ali.CDate then t1.stud_NM else

CASE WHEN orig.CDate=ali.CDate then '1' else null

end

end) Count

from t1,

t2 orig,

t2 ali

where t1.stud_id=orig.stud_id

and t1.stud_id=ali.stud_id

group by t1.stud_NM

order by t1.stud_NM

which is giving the following output, which looks fine as well -

STUD_NM       COUNT
-------- ----------
Andy              1
Chi               1
Derek             2
Ketty             1
Kristien          1
Messi             1
Tom               2
Vikas             1

8 rows selected.

So want to confirm if i am doing right or it is just because of the data it is giving me the right result ?

Kindly help me thanks in advance for your time and efforts.

This post has been answered by Karthick2003 on Jul 4 2013
Jump to Answer
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Aug 1 2013
Added on Jul 4 2013
6 comments
744 views