我有此查询,需要基于branchId的每一行都缺少ActiveAgent。现在确定如何使其与branchId一起使用。当我在查询中有这样的查询时,它将为所有行返回1 amouth,但是当我尝试将其分开并像这样传递branchId时,它将起作用。
…….
,(select Count(*) from [TblAgencyContact] agent
left join [TblBranchMember] branchMember on agent.AgencyContactId = branchMember.AgencyContactId
left join [TblBranch]branch on branch.BranchId = branchMember.BranchId
where agent.StatusId = 1 and branchMember.BranchId = branch.BranchId and
branchMember.BranchId = branch.BranchId) as ActiveAgents
,……
from [TblBranch]branch
我不知道如何在查询中将当前行的BranchId
传递给它。
select
Count(*)
from
[TblAgencyContact] agent
left join
[TblBranchMember] branchMember on agent.AgencyContactId = branchMember.AgencyContactId
left join
[TblBranch] branch on branch.BranchId = branchMember.BranchId
where
agent.StatusId = 1
and branchMember.BranchId = branch.BranchId
and branchMember.BranchId = branch.BranchId
and branch.BranchId = 81
答案 0 :(得分:2)
您的顶部查询已关闭,但是您需要记住,您不需要在TblBranch表上进行JOIN,因为您正在将适当的值传递给子查询。另外,链接不应该是“内部联接”吗?如果TblBranchMember表中没有人,您就不想计算TblAgencyContact行,对吗?
(
select Count(*)
from [TblAgencyContact] agent
INNER join [TblBranchMember] branchMember
on agent.AgencyContactId = branchMember.AgencyContactId
where agent.StatusId = 1
and branchMember.BranchId = branch.BranchId -- where branch is accessed in the outer query
) as ActiveAgents