在嵌套查询中,检查条件的所有值

In a nested query, check all values for a condition

如何摆脱嵌套查询(同意,dis_agreed)?如何重写加入 - 我想不出。或许还有其他最优解?

select *
from (
    select
        (select count(id) from Agreement a where a.ConclusionCardFile = f.id and a.Status = 1) agreed,
        (select count(id) from Agreement a where a.ConclusionCardFile = f.id and (a.Status <> 1 or a.Status is null)) dis_agreed
    from ConclusionCard_Files f
) t
where t.agreed > 0 and dis_agreed = 0

如果我没理解错的话,你可以试试用JOINHAVING条件聚合函数。

SELECT COUNT(CASE WHEN a.Status = 1 THEN ID END) agreed,
       COUNT(CASE WHEN a.Status <> 1 or a.Status is null THEN ID END) dis_agreed
FROM Agreement a 
INNER JOIN ConclusionCard_Files f
ON a.ConclusionCardFile = f.id
HAVING 
    COUNT(CASE WHEN a.Status = 1 THEN ID END) > 0
AND 
   COUNT(CASE WHEN a.Status <> 1 or a.Status is null THEN ID END) = 0

编辑

如果你想根据你的情况从ConclusionCard_Files获取数据。你可以尝试让条件聚合函数在子查询中每个 ConclusionCardFile 来自 table Agreement 然后做 JOIN

SELECT f.*
FROM (
    SELECT COUNT(CASE WHEN a.Status = 1 THEN ID END) agreed,
           COUNT(CASE WHEN a.Status <> 1 or a.Status is null THEN ID END) dis_agreed,
           a.ConclusionCardFile
    FROM Agreement a 
    GROUP BY a.ConclusionCardFile
) a 
INNER JOIN ConclusionCard_Files f
ON a.ConclusionCardFile = f.id
WHERE a.agreed > 0 AND a.dis_agreed = 0

也许您只是使用 sub-queries 来过滤?如何将它们移动到 WHERE 子句?

SELECT 
   *
FROM ConclusionCard_Files f
WHERE 
    EXISTS(select * from  Agreement a where (a.ConclusionCardFile = f.id) and a.Status =1)
    AND NOT EXISTS(select * from  Agreement a where (a.ConclusionCardFile = f.id) and (a.Status != 1 or a.Status is null))  

它的性能友好,因为 SqlServer 不会计算所有计数

您可以将条件写成 where 子句:

select *
from conclusionCard_Files
where exists (
    select *
    from agreement
    where agreement.conclusionCardFile = conclusionCard_Files.id
    having sum(case when status = 1 then 1 else 0 end) > 0
    and    sum(case when status = 1 then 0 else 1 end) = 0
)