SQL查询从密钥连接的两行中获取数据
问题描述:
我有一个问题,起初对我来说似乎很简单,但我对SQL相对较新,但无法解决问题。SQL查询从密钥连接的两行中获取数据
我有两个表:'申请人'和'家庭单位'。
申请人:
ApplicantID | FirstName
----------- | ----------
1 | John
2 | Mary
家庭单位:
ApplicantID | UnitID| Note
1 | 10 | Member
2 | 10 | Mother
我需要在一个表申请人姓名和母亲名字带来。
母亲申请者ID应该通过在同一个表中的家庭单位表和母亲笔记中具有相同的UnitID来确定(以及他们在此不相关的其他细节)。
我尝试此查询:
这显然是行不通的正确,我收到申请人的名字,而不是申请人的母亲的名字。
需要你的帮助,链接文章和解释也将是伟大的,因为我觉得我失去了一些非常基本的东西。
答
; with cte as
(
select fu.*,a.name from
FamilyUnit fu
join applicant a on a.id = fu.id
where type = 'Mother'
)
select a.id,a.name,c.name
from applicant a
join FamilyUnit fu on fu.id = a.id
join cte c on c.unit = fu.unit
where c.id <> a.id
+0
非常感谢。 – InnaS
答
我不是那么肯定,如果这是正确的:只是尝试
select * from
(select * from @family_units where note = 'member') as a
left join
(select * from @family_units where note = 'mother') as b
on a.unitid = b.unitid
left join @applicant_table as c
on a.ApplicantID =c.ApplicantID
测试结果:
1 10 Member 2 10 Mother 1 John
然后呢,这里是你期望的输出? –
我需要得到申请人姓名和母亲姓名在1行 – InnaS
[踢坏的习惯:使用旧式JOIN](http://sqlblog.com/blogs/aaron_bertrand/archive/2009/10/08/bad-habits -to-kick-using-old-style-joins.aspx) - 旧式*逗号分隔的表*样式列表被替换为ANSI - ** 92 **中的*适当的* ANSI'JOIN'语法SQL标准(** 25年**前!),其使用不鼓励 –