0

lets say I have two tables:

TableA
ID,    Time,   Size

0      5:00    600
1      8:00    800
2      7:00    100
3      1:50    140
4      2:40    300 
12     3:40    300

TableB
ID,    Time,   Size

8      5:00    600
1      8:00    800
2      8:00    900
3      1:50    140
5      2:40    300 
12     3:40    300 

Now I would like to compare these two Tables: give all rows from Table A and B where the IDs are same (or lets say where the IDs are existing in both of the Tables) but lower then 12 - so that would kick out table A ID 0, 4, 12 and from table B ID 8, 5, 12

After that I would have only 3 rows left. Now I would like to kick out all rows where there is one or more difference between the whole TableA row ID == TableB row ID

At the end there would be (if I see that correct) as output:

ID,    Time,   Size
1      8:00    800
3      1:50    140

For this solution I need for sure intersect and maybe minus. At first I tought this SQL statement would do what I want:

select * from TableA where ID < 12 intersect select * from TableB where ID < 12 
minus 
select * from TableB where ID < 12;

But this is not working that well. Ist because of the intersect, Im using intersect for the whole row, I should use intersect for only the IDs and IF I have the intersect of the IDs (that would be 1,2,3) then I have to use ID TableA with ID 1,2,3 minus TableB with ID 1,2,3. But how? Or do I miss something? Any ideas? Thank you

sabisabi
  • 1,501
  • 5
  • 22
  • 40

2 Answers2

3

From your requirements and the testdata you've provided, you don't need intersect at all. A mere INNER JOIN would suffice.

SELECT a.* 
FROM   TableA a 
       INNER JOIN TableB b ON b.ID = a.ID AND b.Time = a.Time AND b.Size = a.Size
Lieven Keersmaekers
  • 57,207
  • 13
  • 112
  • 146
1
select id from TableA where ID < 12 and id in (Select id from TableB)
union 
select id from TableB where ID < 12   and id in (Select id from TableA)

or

SELECT id, 
       time, 
       size 
FROM   (SELECT * 
        FROM   tablea 
        WHERE  id < 12 
        UNION ALL
        SELECT * 
        FROM   tableb 
        WHERE  id < 12) a 
GROUP  BY id, 
          time, 
          size 
HAVING Count(*) = 2 

or

SELECT * 
FROM   tablea A 
WHERE  EXISTS (SELECT 1 
               FROM   tableb b 
               WHERE  b.id = a.id 
                      AND b.time = a.time 
                      AND b.size = a.size) 
Romil Kumar Jain
  • 20,239
  • 9
  • 63
  • 92