在笼子里找到野生动物的百分比

时间:2014-11-20 09:04:50

标签: sql postgresql percentage

我有一个子查询,其中包含一个笼子编号和一个动物的类型(野生与否),所有其他列与该问题无关。

我需要显示笼中野生动物的百分比,在随附的Screen-Shot中你可以看到11只笼子中共有4只动物有2只野生动物。

无法记住获得结果的最佳方法,因为我们无法将count()除以count()。

任何帮助将不胜感激。 谢谢。

查询代码:

select *
from animal , cage
where animal.cno = cage.cno  and cage.cno  in(
       select distinct cno
       from  animal  
       where   animal.cno = all
              (select cno
              from animal 
              where   type <> all
                      (select type
                       from animal
                        where type not in ('wolf' , 'sheep',  'Capricorn', 'tiger') )));

表格式:

create table cage 
(cno int primary key, wild boolean, size int,
check (size<=10000));

create table animal
 (aid int, cno int, type varchar(15), wild boolean,
 primary key(aid), 
 foreign key (cno) references cage
    on update cascade
    on delete set null);

广告代码:

insert into cage
values (10,TRUE,1000),
       (11,TRUE,7500),
       (12,FALSE,700),
       (13,FALSE,200);

insert into animal
values(100,10,'monkey',TRUE),
      (110,11,'Sheep',FALSE),
      (120,11,'wolf',TRUE),
      (130,10,'bear',TRUE),
      (140,12,'frog',FALSE),
      (145,10,'dingo',FALSE),
      (160,11, 'Capicorn',FALSE),
      (155,11,'Tiger',TRUE),
      (150,13,'deer',FALSE);

屏幕截图:

enter image description here

屏幕截图链接:

https://www.dropbox.com/s/m14t6o137q5z4gn/Screenshot%202014-11-20%2010.59.16.png?dl=0

1 个答案:

答案 0 :(得分:0)

这样的事情:

select t.cno,
       total_count, 
       wild_animal_count,
       case 
         when wild_animal_count is null then 0
         else wild_animal_count::numeric / total_count::numeric
       end as percentage
from (
   select c.cno, 
          count(*) as total_count, 
          sum(case when a.wild then 1 end) as wild_animal_count
   from animal a
     join cage c on a.cno = c.cno
   group by c.cno
) t
order by t.cno;

内部查询计算笼中的所有动物和笼中野生动物的数量。 外部查询然后简单地划分这些数字。转换为数字(::numeric事物)是必要的,因为否则所有内容都将被计算为整数(因此除法的结果将被舍入)。

SQLFiddle:http://sqlfiddle.com/#!12/12989/3

请注意,我在where子句中使用JOIN部分中的显式from子句替换了过时(且易碎)的隐式连接。你应该真的习惯了。