首页 > 解决方案 > 过滤结果的 SQL 问题

问题描述

我目前得到的结果如下所示:

Row    | ParentLevel | ChildLevel | 
1      |     1       |     1      |   
2      |     2       |     2      |  
3      |     2       |     3      |  

如果没有不匹配的结果,我只希望在父子匹配时出现一行。

在这种情况下,第 1 行很好,因为它是父级别 1 唯一出现的时间

第 2 行我不想出现,因为第 3 行在那里,并且父母和孩子在第 3 行不匹配。

这可以在 where 语句中设置吗?

标签: sqlsql-server

解决方案


您可以使用not exists

select t.*
from t
where t.ParentLevel <> t.ChildLevel or
      not exists (select 1
                  from t t2
                  where t2.ParentLevel = t.ParentLevel and t2.ParentLevel <> t2.ChildLevel
                 );

推荐阅读