Select every field that fullfil the condition

Ray-Von-Mice :

I have a table call production

factory_id | factory_name | product_id
         1 |            A |          1
         1 |            A |          2
         1 |            A |          3
         2 |            B |          3
         3 |            C |          1
         3 |            C |          2
         3 |            C |          3
         3 |            C |          4
         3 |            C |          5

I'm trying to develop a query that will return two factory name pair such that every product of factory1 is produced by factory2, result looked like:

factory_name_1 | factory_name_2
             A |              C
             B |              A
             B |              C

I have some nested self join and renames, but I can't wrap my head around how I can apply EXISTS or IN for this scenario that does "for each product produced by factory X do condition". Thanks to any help in advanced.

Update: Sorry that I forgot to paste my query:

select t0.fname0, t1.fname1
from    (
        select factory_id as fid0, factory_name as fname0, product_id as pid0, count(distinct factory_id, product_id) as pnum0
        from production
        group by factory_id
    ) t0
    join
    (
        select factory_id as fid1, factory_name as fname1, product_id as pid1, count(distinct factory_id, product_id) as pnum1
        from production
        group by factory_id
    ) t1
where t0.fid0 <> t1.fid1
    and t0.pnum0 < t1.pnum1
    and t0.pid0 = t1.pid1;
cars10m :

You need to JOIN the table for each factory pairing to make sure they "join" on the same product_ids, otherwise you might end up with similar counts for DISTINCT product_ids but these will not necessarily refer to the same product_ids.

This is my take on it:

SELECT bfna,afna, pcnt FROM (
   SELECT a.factory_name afna, b.factory_name bfna, COUNT(DISTINCT b.product_id) commoncnt
   FROM tbl a LEFT JOIN tbl b ON b.factory_name!=a.factory_name AND b.product_id=a.product_id 
   GROUP BY a.factory_name, b.factory_name
) c
INNER JOIN (
   SELECT factory_name fna, COUNT(DISTINCT product_id) pcnt
   FROM TBL GROUP BY factory_name
) d ON fna=bfna AND commoncnt=pcnt
ORDER BY bfna,afna

You can find a demo here: https://rextester.com/JJGCK84904

It produces:

bfna    afna    commoncnt
A       C       3
B       A       1
B       C       1

For simplicity I left out the column factory_id as it does not add any information here.

Fun fact: as I am using only "bare-bone" SQL expressions, the above code will run on SQL-Server too without any changes.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=17810&siteId=1