0
我在SQL Server中有一对一关系(申请人,参考)中的两个相关表。SQL Server查看从相关表中获取计数where column =“True”
我想要一个视图,它将从Applicant表中检索所有数据,并向视图中添加另一列,告诉我有多少相关的引用行存在“完成”列为True的位置。
我在SQL Server中有一对一关系(申请人,参考)中的两个相关表。SQL Server查看从相关表中获取计数where column =“True”
我想要一个视图,它将从Applicant表中检索所有数据,并向视图中添加另一列,告诉我有多少相关的引用行存在“完成”列为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
很明显,你需要用我自己制作的列名和外键字段替换成真正的列名。 – RThomas
你给的第一个答案就是我正在寻找的答案。我只是测试它,它似乎工作。 – user1304444