加入 select 假设条件在下一条记录中给出

Joined select assuming criteria given in the next record

我有一个 SQL Server 2012 table,其中包含数十万行地质数据 (请参考下面的屏幕截图)。这些是不同 CountryIDs 的 gCodes 的记录。

我需要 CountryID = 112 的所有 gCode 的加入-select 假设以下条件:

提供的屏幕截图中有两个示例。在这两种情况下:

也就是说我要把这两条记录放到记录集中。

我知道我的查询必须以某种方式在同一个 table 中执行 inner join ... on gCode 但到目前为止,我不知道如何编写查询。我写了一些查询,但没有带来想要的结果。

这是直接翻译成SQL:

with cte1 as
 ( select gCode 
   from tab
   where CountryID = 112
     and xm = xc -- Xm and Xc for CountryID=112 is equal.
 ),
cte2 
 ( select gCode 
   from tab
   where CountryID = 61
     and xc/xm >= 3 -- Xc for CountryID=61 is significantly greater than Xm. At least 200%
 )
select cte1.gCode
from cte1
join cte2
on cte1.gCode = cte2.gCode

我更喜欢相关子查询:

select gCode 
from tab as t1
where CountryID = 112
and xm = xc -- Xm and Xc for CountryID=112 is equal.
and exists
 ( select * 
   from tab as t2
   where t2.gCode = t1.gCode
     and CountryID = 61
     and xc/xm >= 3 -- Xc for CountryID=61 is significantly greater
 )