我在SQL Server中有两个相关的表,一对多关系(申请人,参考)。
我想要一个视图,它将从Applicant表中检索所有数据,并在视图中添加另一列,告诉我“完成”列为True的相关参考行数量。
答案 0 :(得分:0)
使用子查询这样的东西:
select applicantfield1, applicantfield2,
(select count(*) from
reference where reference.applicantkey = applicant.applicantkey
and reference.complete = 1) AS referencecount
from applicant
除非完整字段在申请人表格中(不在参考表格中)。如果是这样,那就更像是这样:
select applicantfield1, applicantfield2,
(select count(*) from
reference where
reference.applicantkey = applicant.applicantkey) AS referencecount
from applicant
where applicant.complete = 1
答案 1 :(得分:0)
如下所示。你需要加入一张桌子。这将处理申请人也没有真正参考的地方。
SELECT A.*, isnull(r.comptotal,0) as CompleteTotal
FROM Applicant as a Left Join
(SELECT ApplicantId, Count(Complete) as comptotal
FROM Reference Where Complete=1 Group by ApplicantID) as r
on a.ApplicantId = r.applicantId