0

我在 SQL Server 中有两个相关的表,存在一对多的关系(申请人、参考)。

我想要一个视图,该视图将从申请人表中检索所有数据,并向视图添加另一列,告诉我有多少相关的参考行,其中“完成”列为真。

4

2 回答 2

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
于 2012-10-15T23:17:38.400 回答
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
于 2012-10-15T23:19:50.587 回答