我有两个相关的表,Branches和BranchStatus。我想要的是找到所有主要分支(由Branches.BranchSubCode = 0表示),其中BranchStatus中的状态字段是' MA'并且所有子分支(由BranchSubCode> 0表示)的状态字段为“NN'”。在我在下面链接的小提琴中提供的示例数据中,这应该意味着我只返回两个分支。
到目前为止,我已经设法找到一种方法来返回主要分支状态为“MA”的所有分支机构。并且至少有一个子分支具有状态' NN'。我也有问题,我的结果是重复的。
这是我尝试过的代码:
true
在我提供的示例数据中,我希望只返回以下BranchCodes:1,2
相反,我的代码当前返回1,1,5,5,8
请参阅此小提琴,了解示例数据等:http://sqlfiddle.com/#!18/90df4/1
答案 0 :(得分:1)
这是最简单的解决方案。只需遵循您的要求
select
a.BranchCode
from
Branches a
join Branches b on a.BranchCode = b.BranchCode
join BranchStatus c on a.ID = c.BranchID
join BranchStatus d on b.ID = d.BranchID
where
a.BranchSubCode = 0
and b.BranchSubCode > 0
and c.Status = 'MA'
group by a.BranchCode
having min(d.Status) = max(d.Status) and min(d.Status) = 'NN'
答案 1 :(得分:0)
尝试运行下面的查询以获取状态字段为“MA”的所有主要分支,并且其所有子分支的状态字段等于“NN”:
SELECT
b1.ID,
b1.BranchCode
FROM Branches AS b1
INNER JOIN BranchStatus AS bs1
ON b1.ID = bs1.ID
WHERE b1.BranchSubCode = 0
AND bs1.[Status] = 'MA'
AND EXISTS (
SELECT COUNT(*)
FROM Branches AS b2
INNER JOIN BranchStatus bs2
ON b2.ID = bs2.ID
WHERE bs2.[Status] = 'NN'
AND b2.ID = b1.ID
);
答案 2 :(得分:0)
这应该有效。
可能比公认的解决方案更有效,但我喜欢公认的解决方案。
SELECT bm.ID, bm.BranchCode, bm.BranchSubCode, bmS.Status
, bs.ID , bs.BranchSubCode, bsS.Status
FROM Branches bm
JOIN Branches bs
on bs.BranchCode = bm.BranchCode
and bm.BranchSubCode = 0
and bs.BranchSubCode > 0
join BranchStatus bmS
on bmS.BranchID = bm.ID
and bmS.Status = 'MA'
join BranchStatus bsS
on bsS.BranchID = bs.ID
and bsS.Status = 'NN'
where not exists ( select 1
from Branches bNot
join BranchStatus bsSnot
on bsSnot.ID = bNot.ID
and bNot.BranchCode = bm.BranchCode
and bNot.BranchSubCode > 0
and bsSnot.Status <> 'NN'
)
更改为select distinct bm.ID