Sql server SQL Server:按列筛选查询表

Sql server SQL Server:按列筛选查询表,sql-server,Sql Server,我有一张我正试图查询的表。它有两个字段,用于指定唯一的ID。对于这个例子,我将使用PersonA、PersonB、PersonC、PersonD。该表表示两个人之间的关系 人员关系表: Row FieldId_01 FieldId_02 ------------------------------ 1 PersonA PersonB 2 PersonA PersonC 3 PersonB PersonA 4 Pe

我有一张我正试图查询的表。它有两个字段,用于指定唯一的ID。对于这个例子,我将使用PersonA、PersonB、PersonC、PersonD。该表表示两个人之间的关系

人员关系表:

Row     FieldId_01  FieldId_02 
------------------------------
1       PersonA     PersonB
2       PersonA     PersonC
3       PersonB     PersonA
4       PersonC     PersonA
5       PersonD     PersonA
人员
表格:

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

这将满足您的需求。我将样本数据包含在临时表中,因此您可以立即对其进行测试:

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
使用
不存在()

如果
FieldId\u 01
与同一行中的
FieldId\u 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)
  )

我不确定问题是什么。。。是否要将关系表修改为只有唯一行?或者你只是想要一个相互关系中的因素“相同”的查询,并从结果集中删除这些因素吗?用我的问题更新了帖子,但仍然完全不清楚你在问什么。这里是一个很好的开始。还有一个澄清。你说你需要一个独特的组合来代表一个人。。。但该示例在每个输入行中显示人物角色。如果有一个将PersonB与PersonD关联的输入行,您是否希望这样,因为它是唯一的?或者,您是在暗示您要筛选“所有涉及角色的唯一行”?换句话说,如果第6行有PersonB/PersonD。。。是否要返回第6行?
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)
       )
  )
+-----+------------+------------+
| Row | FieldId_01 | FieldId_02 |
+-----+------------+------------+
|   1 | PersonA    | PersonB    |
|   2 | PersonA    | PersonC    |
|   5 | PersonD    | PersonA    |
+-----+------------+------------+