2012-11-29 116 views
0

我必須創建一個顯示父親及其平均孩子數量的sql語句。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

謝謝!

+2

您是否嘗試過創建SQL查詢?如果是這樣,請顯示您所寫的查詢,以便我們看到您遇到問題的位置。你不應該只是問人們的代碼... –

+0

告訴我們你已經做了什麼。提示開始:你的例子中甚至沒有'select'。另外,檢查你的教科書是否有「聚合函數」 – Crisfole

+0

我在第一篇文章中添加了它 –

回答

0

這裏的每父親的孩子總數:

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