2017-04-04 146 views
0

我有一個表,我試圖查詢。它有兩個字段,唯一標識。在這個例子中,我將使用PersonA,PersonB,PersonC,PersonD。該表格代表兩個人之間的關係。SQL Server:查詢表按列過濾器

人關係表:

Row  FieldId_01 FieldId_02 
------------------------------ 
1  PersonA  PersonB 
2  PersonA  PersonC 
3  PersonB  PersonA 
4  PersonC  PersonA 
5  PersonD  PersonA 

Person表:

PersonID 
--------- 
PersonA 
PersonB 
PersonC 
PersonD 

我不關心的順序,我只需要參考PersonA的獨特組合。所以,第1行和第3行是相同的,第2行和第4行是相同的,第5行沒有匹配,但仍然是唯一的組合。

我需要選擇一個唯一的組合。

預期的輸出應該

人關係表

Row  FieldId_01 FieldId_02 
------------------------------- 
1  PersonA  PersonB 
2  PersonA  PersonC 
5  PersonD  PersonA 
+0

我不知道問題是什麼...你要修改的關係表中只能有唯一的行?或者你只是想要一個查詢,因爲在互惠關係是「相同的」,並從結果集中消除這些因素? – pmbAustin

+0

用我的問題更新了帖子 –

+1

這裏是一個開始的好地方。 http://spaghettidba.com/2015/04/24/how-to-post-a-t-sql-question-on-a-public-forum/ –

回答

0

這將你在找什麼。我包含在一個臨時表中的樣本數據,因此可以立即對其進行測試:

CREATE TABLE #T (id int not null PRIMARY KEY, companyName varchar(16) not null) 

INSERT INTO #t Values 
(1,  'dogs ltd'), 
(2,  'cats ltd'), 
(3,  'pigs ltd'), 
(4,  'pigs ltd'), 
(5,  'cats ltd'), 
(6,  'cats ltd'), 
(7,  'dogs ltd'), 
(8,  'pigs ltd') 

SELECT id, CompanyName 
FROM (
    SELECT *, 
     LEAD(CompanyName, 1) OVER(ORDER BY id) as nc, 
     LAG(CompanyName, 1) OVER(ORDER BY id) AS pc 
    FROM #t t 
    ) x 
WHERE nc = companyName 
    OR pc = companyName 

我的輸出:

id CompanyName 
3 pigs ltd 
4 pigs ltd 
5 cats ltd 
6 cats ltd 
0

使用not exists()

如果FieldId_01從來都不是一樣的,在FieldId_02同一行,則:

select * 
from t 
where not exists (
    select 1 
    from t as i 
    where i.Row < t.Row 
    and i.FieldId_01 in (t.FieldId_01,t.FieldId_02) 
    and i.FieldId_02 in (t.FieldId_01,t.FieldId_02) 
) 

否則

select * 
from t 
where not exists (
    select 1 
    from t as i 
    where i.Row < t.Row 
    and ((i.FieldId_01 = t.FieldId_01 and i.FieldId_02 = t.FieldId_02) 
     or (i.FieldId_02 = t.FieldId_01 and i.FieldId_01 = t.FieldId_02) 
     ) 
) 

rextester演示:http://rextester.com/SQL61250

都返回:

+-----+------------+------------+ 
| Row | FieldId_01 | FieldId_02 | 
+-----+------------+------------+ 
| 1 | PersonA | PersonB | 
| 2 | PersonA | PersonC | 
| 5 | PersonD | PersonA | 
+-----+------------+------------+