SQL具有多个值的字段的递归匹配

时间:2017-06-30 10:13:45

标签: sql sql-server

我有一张这样的表(这是简化的)

ID | FOO | BAR
--------------
 1 | 100 | 200
 1 | 101 | 202
 1 | 102 | 205
 2 | 100 | 200
 2 | 101 | 222
 2 | 102 | 203
 3 | 100 | 201
 3 | 101 | 202
 3 | 102 | 204
 4 | 100 | 201
 4 | 101 | 202
 4 | 102 | 205

如果我查询 FOO = 100且BAR = 200 ,则返回的ID为1和2,这样就可以了。

我希望能够 FOO = 100且BAR = 200 然后 FOO = 101且BAR = 202 所以我只返回ID = 1

如果我 FOO = 100且BAR = 201 FOO = 101 AND BAR = 202 FOO = 102且BAR = 205 我只会被退回ID 4

如果我 FOO = 100且BAR = 201 ,我会看到ID 3和4

我认为我应该能够使用类似于Recurisve query in SQL Server的递归_CTE来做到这一点,但我不能让我知道如何构建它。

FOO所能达到的水平也不限于3,只是为了这个例子而被简化了

2 个答案:

答案 0 :(得分:0)

无需递归CTE。 FOR FOO = 100且BAR = 200然后FOO = 101且BAR = 202,你可以这样做。

with cte
as
(

SELECT ID,FOO,BAR
FROM TAB
WHERE FOO = 100 and BAR = 200
)
SELECT ID
FROM cte
WHERE FOO=101 and BAR = 202

对于FOO = 100且BAR = 201且FOO = 101 AND BAR = 202且FOO = 102且BAR = 205,您可以这样做:

with cte
    as
    (

    SELECT ID,FOO,BAR
    FROM TAB
    WHERE FOO = 100 and BAR = 201
    )
    SELECT ID 
    FROM
    (SELECT ID,FOO,BAR
    FROM cte
    WHERE FOO=101 and BAR = 202
    ) result(ID,FOO,BAR)
    WHERE FOO=102 and BAR = 205

答案 1 :(得分:0)

如果我理解正确,那么每种情况都需要共同的ID

如果是,并且每个FOO, BAR ID是唯一的,那么您可以这样做:

with the_table(ID, FOO, BAR) as(
select  1 , 100 , 200 union all
select   1 , 101 , 202 union all
select   1 , 102 , 205 union all
select   2 , 100 , 200 union all
select   2 , 101 , 222 union all
select   2 , 102 , 203 union all
select   3 , 100 , 201 union all
select   3 , 101 , 202 union all
select   3 , 102 , 204 union all
select   4 , 100 , 201 union all
select   4 , 101 , 202 union all
select   4 , 102 , 205
)


select id from the_table
where
(FOO = 100 and BAR = 201) or
(FOO = 101 AND BAR = 202) or
(FOO = 102 and BAR = 205)
group by id
having count(*) = 3

请注意:count(*) = 3,数字3where子句中条件的计数,例如,如果您只有一个条件(FOO = 100 and BAR = 201),则查询为:< / p>

select id from the_table
where
(FOO = 100 and BAR = 201)
group by id
having count(*) = 1