SQL - 划分两个结果

时间:2012-09-08 19:48:11

标签: sql oracle oracle-sqldeveloper

下面有两个查询,两个都来自同一个“玩家”表。我想通过查询2划分查询1以获得相关百分比。我对更详细的SQL查询相对较新,以及在论坛上发帖......但如果您对如何将其结合起来获得相关百分比结果有任何建议,请告诉我。

1

Select
  sysdate,sum(Count(init_dtime))
From Player p
Where
  Trunc(Init_Dtime) > Trunc(Sysdate) - 7 
  And Trunc(Create_Dtime) >= To_Date('2012-mar-01','yyyy-mon-dd')
  and trunc(create_dtime) < to_date('2015-sep-9','yyyy-mon-dd')
Group By Trunc(Init_Dtime)
Order By Trunc(Init_Dtime) Asc

2

Select
  Sum(Count(Create_Dtime))
From Player P
where 
  Trunc(Create_Dtime) >= To_Date('2012-mar-01','yyyy-mon-dd')
  And Trunc(Create_Dtime) < To_Date('2015-sep-9','yyyy-mon-dd')
Group By Trunc(create_Dtime)
Order By Trunc(create_Dtime) Asc

1 个答案:

答案 0 :(得分:5)

你可以说

select sysdate,
       count((init_dtime)) / sum((Create_Dtime)) * 100 as percentage
  from Player p
 where Trunc(Init_Dtime) > Trunc(Sysdate) - 7 
   and Trunc(Create_Dtime) >= To_Date('2012-mar-01','yyyy-mon-dd')
   and trunc(create_dtime) < to_date('2015-sep-9','yyyy-mon-dd')
   order by percentage asc

不需要SQL中的group by,因为您实际上并没有按某种方式进行分组。例如,当你需要玩家百分比时,group by非常有用。然后你会说group by player_id并且select会有player_id

select player_id, count(…)
  from …
 where …
group by player_id

编辑: 如果where子句不同:

select sysdate, 
       (
           (select count((init_dtime))
             from player p
            where trunc(Init_Dtime) > trunc(Sysdate) - 7 
              and Trunc(Create_Dtime) >= To_Date('2012-mar-01','yyyy-mon-dd')
              and trunc(create_dtime) < to_date('2015-sep-9','yyyy-mon-dd'))
            / 
           (select count((Create_Dtime))
              from player P
             where trunc(Create_Dtime) >= To_Date('2012-mar-01','yyyy-mon-dd')
               and trunc(Create_Dtime) < To_Date('2015-sep-9','yyyy-mon-dd'))
       ) * 100 as percentage
from dual