SQL查找同一表中缺少的组合

时间:2018-10-11 20:27:46

标签: 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        'Inactive'  3
3        'Inactive'  1
3        'Inactive'  2

3 个答案:

答案 0 :(得分:1)

使用cross join获取所有组合。然后过滤掉存在的那些

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;

答案 1 :(得分:0)

您可以使用#include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <string.h> #include <netdb.h> #include <arpa/inet.h> #include <netinet/in.h> int main(int argc, char *argv[]) { int listenSocket, status, socketClient; unsigned short int msgLength; struct addrinfo hints, *servinfo; struct sockaddr_in clientAddress; socklen_t clientAddressLength = sizeof clientAddress; char msg[101]; //Test port number if (argc != 2) { fprintf(stderr,"Usage : %s [NUMERO_PORT]\n",argv[0]); return 2; } memset(&hints, 0, sizeof hints); hints.ai_family = AF_INET; // IPv4 hints.ai_socktype = SOCK_DGRAM; // UDP hints.ai_flags = 0; //Car on fait le test sur la meme machine if ((status = getaddrinfo(NULL, argv[1], &hints, &servinfo)) != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(status)); return 3; } if ((listenSocket = socket(servinfo->ai_family, servinfo- >ai_socktype, servinfo->ai_protocol)) == -1) { perror("socket:"); return 4; } if (bind(listenSocket, servinfo->ai_addr, servinfo->ai_addrlen) == -1) { close(listenSocket); perror("bind:"); return 5; } listen(listenSocket,5); int sizeOfSockAddr = sizeof(clientAddress); socketClient= accept(listenSocket, NULL, NULL); if (socketClient < 0) { fprintf(stderr,"Erreur accept\n"); return 6; } freeaddrinfo(servinfo); printf("Waiting for a client's request %s\n", argv[1]); while (1) { //some things } }` CROSS JOIN

EXCEPT

db<>fiddle demo

答案 2 :(得分:0)

您可以在this manner中使用CROSS JOIN

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