SQL Server视图从列为“的相关表中获取计数”;“真的”;
我在SQL Server中有两个相关的表,它们是1对多关系(申请人、参考人)SQL Server视图从列为“的相关表中获取计数”;“真的”;,sql,sql-server,sql-view,Sql,Sql Server,Sql View,我在SQL Server中有两个相关的表,它们是1对多关系(申请人、参考人) 我需要一个视图,该视图将检索申请者表中的所有数据,并向该视图添加另一列,该列告诉我在“Complete”列为True的位置有多少个相关的引用行。使用子查询执行类似操作: select applicantfield1, applicantfield2, (select count(*) from reference where reference.applicantkey = applicant.applic
我需要一个视图,该视图将检索申请者表中的所有数据,并向该视图添加另一列,该列告诉我在“Complete”列为True的位置有多少个相关的引用行。使用子查询执行类似操作:
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
类似下面的例子。你需要在一张桌子上加入。这将处理申请人也没有真实参考的情况
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
显然,您需要用真实的列名和外键字段替换我编造的列名和外键字段。您给出的第一个答案就是我正在寻找的答案。我刚刚测试过它,它似乎在工作。