Oracle找到股东子查询

时间:2012-07-30 20:09:20

标签: sql oracle

试图找到持有任何一家公司0.5%以上股份的所有股东 这是我的查询我相信我也很接近所附的图像有架构

![Select  Sh.Share_Holder_Id Shareholderid,
       Sh.First_Name||' '||Sh.Last_Name Shareholders, 
       c.name,
       sum(T.Share_Amount) ShareAmount
    From Trades T  
      Inner Join 
      Share_Holders Sh 
        On 
          T.Share_Holder_Id =Sh.Share_Holder_Id
      Inner Join
      Shares S
        On
      S.Share_Id =T.Share_Id
      Inner Join 
      Companies C
        on
      C.Company_Id=S.Company_Id
              Where exists (
          Select 
             sum(case when shs.amount IS NULL THEN 1 ELSE 0 END)/count (*)*100
   From Shares S1
      Inner Join Share_Holder_Shares shs
        On 
Shs.Share_Id=S1.Share_Id
        --   where  Shs.Amount/t.share_amount * 100 > 0.5
)
Group By Sh.Share_Holder_Id,Sh.First_Name||' '||Sh.Last_Name,C.Name
order by Shareholderid;

shema

1 个答案:

答案 0 :(得分:1)

试试这个解决方案;它使用RATIO_TO_REPORT

SELECT   y.share_holder_id
,        y.shareholders
,        y.portion_of_co
,        y.company_name
FROM    (SELECT x.share_holder_id
         ,      x.shareholders
         ,      RATIO_TO_REPORT(x.share_amount) 
                OVER (PARTITION BY x.company_id) portion_of_co
         ,      c.name                           company_name
         FROM  (SELECT  sh.share_holder_id
                ,       sh.first_name
                        || ' '
                        || sh.last_name     shareholders
                ,       s.company_id
                ,       SUM(t.share_amount) share_amount
                FROM    trades t
                INNER JOIN share_holders sh
                ON         t.share_holder_id = sh.share_holder_id
                INNER JOIN shares        s
                ON         s.share_id = t.share_id
                GROUP BY   sh.share_holder_id
                ,          sh.first_name 
                           || ' '
                           || sh.last_name
                ,          s.company_id
                ) x
         INNER JOIN companies c
         ON         x.company_id = c.company_id
         ) y
WHERE    y.portion_of_co > 0.005
ORDER BY y.share_holder_id
;