0

父親とその平均子供の数を示すSQLステートメントを作成する必要があります。

これは私のSQLスクリプトです:

create table breeder (
breederNumber   number(3) primary key,
name            varchar2(20),
residence       varchar2(20),
password        varchar2(20)
);

create table race (
raceCode        varchar2(2) primary key,
raceName        varchar2(20) not null
);

create table sheep (
earTagNumber    number(2) primary key,
father          number(2),
mother          number(2),
raceCode        varchar2(2),
name            varchar2(20),
previousBreeder number(3),
genotype        varchar2(7),
gender          varchar2(1) check (gender = 'M' OR gender = 'F'),

constraint fk_previousBreeder foreign key (previousBreeder) references breeder(breederNummer) on delete cascade,
constraint rk_raceCode foreign key (raceCode) references race(raceCode) on delete cascade,
constraint fk_mother foreign key (mother) references sheep(earTagNumber) on delete cascade,
constraint fk_father foreign key (father) references sheep(earTagNumber) on delete cascade
);

これは私がこれまでに持っているものです:

select (s1.father), avg(s2.earTagNumber) as averageNumberOfKids
from sheep s1
join sheep s2 on s1.earTagNumber= s2.father
group by s1.father;

私が得たものを出力します:

FATHER AVERAGENUMBEROFKIDS
------ -------------------
                      6.75 

誰か助けてもらえますか?

いくつかのテストデータ:http://pastie.org/5452411

前もって感謝します!

4

1 に答える 1

0

父親1人あたりの子供の総数は次のとおりです。

Select 
  fathers.EarTagNumber,
  fathers.Name,
  Count(*) As NumberOfKids
From
  sheep fathers
    Inner Join 
  sheep children
    On fathers.earTagNumber = children.father
Group By
  fathers.EarTagNumber,
  fathers.Name;

これが子供の平均数です(子供の総数/父親の数)

Select
  Avg(NumberOfKids) As AvgKids
From (
  Select 
    fathers.EarTagNumber,
    Count(*) As NumberOfKids
  From
    sheep fathers
      Inner Join 
    sheep children
      On fathers.earTagNumber = children.father
  Group By
    fathers.EarTagNumber
) a;  

http://sqlfiddle.com/#!4/e5121/10

于 2012-11-29T13:30:07.907 に答える