我有一个必须创建教堂数据库的项目。创建后,我必须进行SQL查询以查找所有10岁以下儿童的单亲父母。
我在“会员”表中有一个婚姻状况列,我曾用它来查找单亲父母,其中有两个。但是,一旦我将其删除,年龄检查将无法进行。下面是单亲检查。
--inner join Children c on c.Father_Id = p.Member_Id
--or c.Mother_Id = p.Member_Id
select p.[First Name]
from Members p, Children c
where p.[Marital Status] = 1 and (GETDATE() - c.Birthday) > 10
我希望只列出两个父母。
编辑1.完整查询:
select distinct p.[First Name]
from Members p
inner join Children c on c.Father_Id = p.Member_Id
or c.Mother_Id = p.Member_Id
where p.[Marital Status] = 1 and (GETDATE() - c.Birthday) > 10
编辑2.样本数据 Sample Data
编辑3。目标是仅看到10岁以下儿童的单亲父母,因此在此唯一应显示的记录应该是Kim&Thomas
答案 0 :(得分:1)
您应该使用< 10
而不是> 10
:
select distinct p.[First Name]
from Members p
inner join Children c on c.Father_Id = p.Member_Id
or c.Mother_Id = p.Member_Id
where p.[Marital Status] = 1 and (GETDATE() - c.Birthday) < 10
答案 1 :(得分:1)
这给您一个成员:
select * from dbo.Members m
where m.[Marital Status] = 1
这会给您10岁以下的孩子:
select * from dbo.Children c
where DATEDIFF(year, GETDATE(), c.Birthday) < 10
现在您需要将它们放在一起,看起来就像是Member_Id = Father_Id或Member_Id = Mother_Id,为了简单起见,我会使用COALESCE():
select m.* from dbo.Members m
inner join dbo.Children c on COALESCE(c.Father_Id, c.Mother_Id) = m.Member_Id
where m.[Marital Status] = 1
and DATEDIFF(year, GETDATE(), c.Birthday) < 10
您也可以只查看具有NULL Mother_Id或NULL Father_Id的孩子,因为这似乎表明一个孩子有1个父母,而没有另一个。
select * from dbo.Children c
where (c.Mother_Id is null or c.Father_Id is null)
and DATEDIFF(year, GETDATE(), c.Birthday) < 10
答案 2 :(得分:0)
使用日期差异功能。
select distinct p.[First Name]
from Members p
inner join Children c on c.Father_Id = p.Member_Id
or c.Mother_Id = p.Member_Id
where p.[Marital Status] = 1 and DATEDIFF(year, c.Birthday, GETDATE()) > 10