2017-04-21 65 views
0

今天,我們正在研究SQL服務器查詢並面向一個簡單邏輯中的一個小問題。我們有一張有3列的桌子。你可以看到下面給出的表的結構。根據不同組合篩選表中的數據

ID | Name | FKId 
1  a  1 
2  b  1 
3  c  1 
4  a  2 
5  b  2 
6  a  3 
7  c  3 
8  b  5 
9  c  5 

在上表中,可以看到一列「名稱」它有三個不同類型的值的A,B,C和「FKId」是一個外鍵列。在我們的結果中,我們需要這些行,其中'姓名'列值組合爲a,b和a,c代表每個'FKId'。沒有其他組合被接受。在上表中,我們需要下面的結果。

ID | Name | FKId 
4  a  2 
5  b  2 
6  a  3 
7  c  3 
+0

是''Name'內FKId'獨特? –

+0

在發佈之前,您是否已經努力做好自己的功課? –

+0

是的,名稱和FKId的組合應該是唯一的。 –

回答

1

我會做這樣的事情:

with fkids as (
    select fkid, 
      max(case when name='a' then 1 else 0 end) as has_a, 
      max(case when name='b' then 1 else 0 end) as has_b, 
      max(case when name='c' then 1 else 0 end) as has_c 
     from table 
     group by fkid 
) 
select table.* from table 
    join fkids on 
     fkids.fkid = table.fkid and (
      (has_a = 1 and has_b = 1 and has_c = 0) or 
      (has_a = 1 and has_b = 0 and has_c = 1) 
     )