SQL在同一个表中查找缺少的组合
我有一张包含以下信息的表格:SQL在同一个表中查找缺少的组合,sql,sql-server,Sql,Sql Server,我有一张包含以下信息的表格: GroupId GroupName PersonId 1 'Inactive' 1 2 'Inactive' 2 3 'Inactive' 3 我想按组建立一个新的失踪人员表,如: GroupId GroupName PersonId 1 'Inactive' 2 1 'Inactive' 3 2 'Inactive' 1 2 'Inactiv
GroupId GroupName PersonId
1 'Inactive' 1
2 'Inactive' 2
3 'Inactive' 3
我想按组建立一个新的失踪人员表,如:
GroupId GroupName PersonId
1 'Inactive' 2
1 'Inactive' 3
2 'Inactive' 1
2 'Inactive' 3
3 'Inactive' 1
3 'Inactive' 2
使用
交叉连接
获取所有组合。然后过滤掉现有的:
select g.groupId, gn.groupName, p.personId
from (select distinct groupId from t) g cross join
(select distinct groupName from t) gn cross join
(select distinct PersonId from t) p left join
t
on t.groupId = g.groupid and
t.groupName = gn.groupName and
t.personId = p.personId
where t.groupId is null;
您可以使用
交叉连接
和,但
除外:
SELECT t1.GroupId, t2.GroupName, t3.PersonId FROM tab t1, tab t2, tab t3
EXCEPT
SELECT GroupId, GroupName, PersonId FROM tab;
您可以在以下位置使用
交叉连接
:
with t( GroupId , GroupName, PersonId ) as
(
select 1, 'Inactive', 1 union all
select 2, 'Inactive', 2 union all
select 3, 'Inactive', 3
)
select t1.GroupId , t1.GroupName, t2.PersonId
from t t1 cross join t t2
where t1.GroupId != t2.PersonId;
GroupId GroupName PersonId
1 Inactive 2
1 Inactive 3
2 Inactive 1
2 Inactive 3
3 Inactive 1
3 Inactive 2