-1

I joined two tables

SELECT 
    t1.column1, 
    t2.column2  
FROM 
    t1 JOIN t2 cu 
        ON t1.id = t2.id AND t1.col LIKE 'A%'  



SELECT
    t1.column1, 
    t2.column2  
FROM
    t1 JOIN t2 cu 
        ON t1.id = t2.id AND t1.col LIKE 'B%' 

How could i intersect these tables so I can have the following output (ids that have both the A% and B%)

join 1

id | col
---┼------
1  | Axxxx
2  | Axxxx

join 2

id | col
---┼-------
1  | Bxxxx
3  | Bxxxx

Final output

id | col
---┼-------
1  | Axxxx
1  | Bxxxx

Thank you

Ejaz
  • 8,719
  • 3
  • 34
  • 49
gabi906
  • 374
  • 1
  • 4
  • 15

3 Answers3

2

If I understood correctly, and what you want is only the ID's that have both A% and B%, then this is your answer

SELECT 
t1.column1, 
t2.column2  
FROM 
t1 JOIN t2 cu 
    ON t1.id = t2.id AND ((t1.col LIKE 'A%'  AND t2.col like 'B%')
    OR (t1.col LIKE 'B%' AND t2.col like 'A%'))
sagi
  • 40,026
  • 6
  • 59
  • 84
1

Based on your sample you don't need intersect but a simple union

 SELECT 
  t1.column1, 
  t2.column2  
FROM 
  t1 JOIN t2 cu 
      ON t1.id = t2.id AND t1.col LIKE 'A%'  

union

SELECT
  t1.column1, 
  t2.column2  
FROM
  t1 JOIN t2 cu 
      ON t1.id = t2.id AND t1.col LIKE 'B%' 

adapt the sintax for union at your db/sql

ScaisEdge
  • 131,976
  • 10
  • 91
  • 107
1

Also try it this way ... as you are looking for only repeatable IDs ... you could just count them from inner select

select column1, column2 from (
     select column1, column2, count(column1) over (partition by column1) [Counted] from (
        SELECT 
           t1.column1, 
           t2.column2  
        FROM 
        t1 JOIN t2 cu 
            ON t1.id = t2.id AND t1.col LIKE 'A%'
     UNION
        SELECT
           t1.column1, 
           t2.column2  
        FROM
           t1 JOIN t2 cu 
           ON t1.id = t2.id AND t1.col LIKE 'B%' 
    ) src
) src2 where Counted > 1
Veljko89
  • 1,813
  • 3
  • 28
  • 43