Need a way to find matches between two many-to-many-relationships

前端 未结 3 1627
Happy的楠姐
Happy的楠姐 2021-01-29 12:11

Given the following tables:

   ------------     ------------
   |     BA   |     |    CA    | 
   ------+-----     ------+-----
   | BId|| AId|     | CId|| AId|
         


        
3条回答
  •  庸人自扰
    2021-01-29 12:38

    One way to do this is to use JOIN and COUNT. You first count the CIds (how many times each one of them is repeated). Then, you do the same for BIds. Then, you JOIN BA and link both (AIds) and COUNT. Your target is to match the count of ids and their AIds.

    Example :

    DECLARE 
        @a TABLE(id INT)
    
    INSERT INTO @a VALUES 
    (1),
    (2),
    (3),
    (4),
    (5),
    (6)
    
    DECLARE 
        @b TABLE(id CHAR(2))
    
    INSERT INTO @b VALUES 
    ('B1'),
    ('B2'),
    ('B3')
    
    DECLARE 
        @c TABLE(id CHAR(2))
    
    INSERT INTO @c VALUES 
    ('C1'),
    ('C2'),
    ('C3')
    
    
    DECLARE 
        @ba TABLE(BId CHAR(2), AId INT)
    
    INSERT INTO @ba VALUES 
    ('B1',2),
    ('B1', 3),
    ('B2', 2),
    ('B2', 4),
    ('B2', 5)
    
    DECLARE 
        @ca TABLE(CId CHAR(2), AId INT)
    
    INSERT INTO @ca VALUES 
    ('C1',2),
    ('C2',2),
    ('C2',3),
    ('C3',4),
    ('C3',5)
    
    
    
    
    SELECT DISTINCT CId 
    FROM (
    SELECT *
    ,   COUNT(*) OVER(PARTITION BY CId) cnt
    FROM @ca ca
    ) c
    LEFT JOIN (
        SELECT *
        ,   COUNT(*) OVER(PARTITION BY BId) cnt
        FROM @ba ba
    ) b ON b.AId = c.AId AND b.cnt = c.cnt 
    WHERE 
        b.cnt IS NOT NULL 
    

    So, in the example C2 has repeated 2 times, and in BA, B1 has repeated also 2 times. This is the first condition, second one is to match both AIds, if they're the same, then you have a group match.

提交回复
热议问题