2017-06-30 73 views
1

我有一個這樣的表(這是簡化的)SQL遞歸匹配具有多個值

 
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 = 201FOO = 101和BAR = 202FOO = 102和BAR = 205我將只被返回ID 4

如果我沒有FOO = 100和BAR = 201我會看到ID 3和4

我認爲我應該能夠做到這一點遞歸_CTE類似Recurisve query in SQL Server但我不能讓我頭像如何構造它。

是FOO可以去太水平不限於3它只是被簡化,這個例子

+1

你能分享你的查詢和預期的輸出? – TriV

回答

0

如果我正確理解,你需要共同的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 

注:

如果是這樣,如果FOO, BAR是每ID唯一的,那麼你就可以做到這一點count(*) = 3,數3是條件計數where條款,例如,如果你有隻是一個條件(FOO = 100 and BAR = 201),然後查詢是:

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

感謝這將做我所需要的,我知道有多少'或'查詢我會有,但你會動態地建立查詢。 – Gushie

0

無需遞歸CTE。對於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和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 
+0

如果我構造該查詢爲

;with _cte as ( \t SELECT ID \t FROM TAB \t WHERE foo = 100 AND BAR = 200 ) select * from _CTE join TAB on TAB.id = _cte.id WHERE TAB.foo = 101 AND TAB .bar=202
它確實讓我有一部分途徑,但我需要能夠對結果應用三級過濾器,例如如果FOO = 102且BAR = 205 – Gushie

+0

您可以使用嵌套查詢。查看更新回答 –