SQL选择祖父母

时间:2015-12-08 20:44:25

标签: sql sql-server join

我对我的sql课程有一个问题,即选择所有有孙子的人并列出他们有多少人

    CREATE TABLE person (
  persID INT IDENTITY(1,1),
  persFName VARCHAR(30) NOT NULL,
  persLName VARCHAR(30) NOT NULL,
  persDOB DATE,
  motherID INT,
  fatherID INT,
  persDOD DATE,
  persGender CHAR(1),

  PRIMARY KEY (persID)
);

CREATE TABLE couple (
  coupleID INT IDENTITY(1,1),
  alphaSpouse INT NOT NULL,
  omegaSpouse INT NOT NULL,
  coupleStart DATE NOT NULL,
  coupleEnd DATE,

  PRIMARY KEY (coupleID),
  FOREIGN KEY (alphaSpouse) REFERENCES person(persID),
  FOREIGN KEY (omegaSpouse) REFERENCES person(persID)
);

这是我的查询,目前它正在获取一些数据,但不是全部,而且不确定我哪里出错了:(

select (p.persFName+' '+p.persLName) as GrandParent, count(*) as Number_Of_Grandchildren --gets all the grandmothers
from person as p
join person as c on c.motherID=p.persID
join person as gm on gm.motherID=c.persID
where p.motherID is null
group by (p.persFName+' '+p.persLName)
union
select (p.persFName+' '+p.persLName) as GrandParent, count(*) as Number_Of_Grandchildren --gets all the grandfathers
from person as p
join person as d on d.fatherID=p.persID
join person as gf on gf.fatherID=d.persID
where p.fatherID is null
group by (p.persFName+' '+p.persLName);

1 个答案:

答案 0 :(得分:4)

您的查询仅选择母亲的母亲和父亲的父亲作为祖父母。

不要将你的查询分成特定的血统(父亲的父亲,父亲的母亲等),只需加入“如果这个人是母亲或父亲”:

from person as p
join person as  c on ( c.motherID = p.persID OR  c.fatherID = p.persID)
join person as gm on (gm.motherID = c.persID OR gm.fatherID = c.persID)

请注意,结果可能需要扣除,特别是如果这些家谱中有任何“近亲繁殖”。