Skip to content
Advertisement

How can I compare rows of two similar tables in SQL?

These TSQL tables are exact but I can’t guarantee that. I cannot guarantee which rows will be non-existent in either table.

Image of both tables

What I want to be able to do is to subtract one from the other into a new table. For instance, “Agg Asslt” should have a column value for “OffenseCount” of 6. However, “Theft Veh” should be -25. If a row does not exist in one or the other table, I will be either subtracting 0 or subtracting from 0. These are always integers. I hope this makes sense. If the row does not exist in either table, the point is moot. Thank you in advance.

Advertisement

Answer

You seem to want a full join:

select coalesce(t1.offense, t2.offense),
       coalesce(t1.count, 0) - coalesce(t2.count, 0)
from table1 t1 full join
     table2 t2
     on t1.offense = t2.offense
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement