2011-12-14 72 views
-2

我有四个表。表格如下。Oracle多表SQL查询

inv_profile:

accnt_no  ac_name1 
    23   Prasun Kanti 
    45   Babu 

psdr_cds:(用于购买)

accnt_no  no_shares   trans_dt   comp_cd 
23    40    1-jan-2006   101 
45    70    11-dec-2011  101 
23    20    1-nov-2011   101 

swr_cds(用于出售)

accnt_no  no_shares   trans_dt  comp_cd 
    23    20    1-jan-2007  101 
    45    20    12-dec-2011  101 
    23    30    15-nov-2011  101 

补偿

comp_cd  comp_nm 
     101   AB BANK 

现在我需要的SQL查询返回的结果如下:

Accnt_no  Name    Total Buy  Total Sale  Balance 

    23  Prasun Kanti  60   50    10 
    45  Babu    70   20    50 

回答

0
with t as 
(select ip.accnt_no, ip.ac_name1, ps.no_shares buy, sw..no_shares sale 
    from inv_profile ip, psdr_cds ps, swr_cds sw 
    where ip.accnt_no = ps.accnt_no) 
select t.accnt_no Accnt_no, 
     t.ac_name1 Name, 
     sum(t.buy) Total_buy, 
     sum(t.sale) Total_sale 
     (sum(t.buy)-sum(t.sale)) Balance 
    from t 
group by t.accnt_no, t.ac_name1 

就行了。但还有很多其他的方法,例如。 over partition by

HTH

+0

尊敬的先生,此查询所示的这个报告用户请求的中断或检测到EOF。 – prasun 2011-12-15 05:36:12

+1

然后您中断了查询和/或丢失了数据库连接。 – 2011-12-15 09:00:27

1
SELECT 
    i.acct_no AS "Accnt_no", 
    i.ac_name1 AS "Name", 
    SUM(p.no_shares) AS "Total Buy", 
    SUM(s.no_shares) AS "Total Sale", 
    SUM(p.no_shares) - SUM(s.no_shares) AS "Balance" 
FROM inv_profile i 
INNER JOIN psdr_cds p ON i.accnt_no = p.accnt_no 
INNER JOIN swr_cds s ON i.accnt_no = s.accnt_no 
GROUP BY i.acct_no, i.ac_name1