Sunday 29 September 2013

Creating an inilne view in SQL,PL/SQL

Here is an example of an inline view SQL.
Lets take for example three tables/

1. tbl_withdrawdeposit
    memb_id  -- reference to p_k to tbl_member_master
    trans_date  --Date of transaction
    amount       -- Amount of transaction
    transaction_type -- Type of Transaction ('W'-withgdrawal, 'D' - deposit
 2. tbl_loansvr
    memb_id  -- reference to p_k to tbl_member_master
    trans_date  --Date of transaction
    amount       -- Amount of transaction
    transaction_type -- Type of Transaction ('W'-withgdrawal, 'D' - deposit

3. tbl_member_master
    member_id   member_id primary key
    member_name  --name of the member
    acc_no              -- account number of the member

 we are going to write an inline view that will show the name,account number of all the member who
 have deposited amount/ returned loan amount more than 1,00,00,00 in the year 2012


select A.acc_no,member_name from
(
(select a.acc_no,a.member_name,nvl(b.amount,0) amount
 from tbl_member_master a,tbl_loansvr b
 where b.memb_id = a.memb_id
 and to_char(trans_date,'rrrr'')='2012'
 and trans_type='D'

union
(
select a.acc_no,a.member_name,nvl(b.amount,0) amount
 from tbl_member_master a,tbl_withdrawdeposit b
 where b.memb_id = a.memb_id
 and to_char(trans_date,'rrrr'')='2012'

)  tbl_all

group by tbl_all.acc_no,tbl_all.member_name
having sum(tbl_all.amount)>1000000

We have created an inline view by union of two tabl and selected acc_no and member_name from
that view naming it tbl_all. Added summed up amount to having clause, grouping by acc_no and member_name, (iline view can contain record from both the table for a single member.).


No comments: