首页 > 解决方案 > 加入 2 个查询

问题描述

我有一个查询,它根据我的 where 条件(一个 varchar,例如 20200227Abc)给我结果。

我使用相同的查询运行这些查询的联合,但将 Where 条件更改为 (20200126xyz)。

我想如果两个条件都存在数据,那么只有给我第一个查询 where (20200227abc) 的结果。

请指教。

标签: sqldatabasesql-query-store

解决方案


如果我正确理解您的问题,那么您希望仅在条件 1 也满足条件 2 时才能获得结果。在这种情况下,您可以使用存在。使用示例:

;with cte as
(select 1 as id,'20200227Abc' as val union
select 1 as id,'20200126xyz' as val union
select 2 as id,'20200227Abc' as val)

select * 
from cte a
where val='20200227Abc' and 
    exists (select 1 from cte b where b.val='20200126xyz' and a.id=b.id)

这应该会给你想要的结果。


推荐阅读