Query - Comparison of Distinct Bases with equal columns

Asked

Viewed 96 times

2

How would a query that selects between two tables according to the value of a specific column ?

For example: I have two tables that contain account number and Balance, I need to know which accounts do not have the same balance.

Tab1
Conta Saldo
123   100,00

Tab2
Conta Saldo
123   150,00

In case I need to know which accounts are not with the hitting balance.

1 answer

1


Depending on the DBMS you use, you will use the "MINUS" or "EXCEPT" function. In the case of SQL Server, your query would look like this:

SELECT Conta, Saldo FROM Tab1 EXCEPT SELECT Conta, Saldo from Tab2.

If you also want to know the different records between the two tables (number of the accounts that exist in one and not in the other) you can also do the following:

Accounts in table 1 and not in 2:

Select tabela1.conta, tabela1.saldo From tabela1 Left Join Tabela2 On tabela2.conta = tabela1.conta Where tabela2.conta Is Null 

Accounts in table 2 and not in 1:

Select tab2.conta, tab2.saldo From tab2 Left Join Tab1 On tab1.conta = tab2.conta Where tab1.conta Is Null 
  • 1

    This helps but with caveats: the tables must be equal or Tab1 not have more columns than Tab2. And will return which records in Tab1 have equal balance in Tab2, not the missing.

  • 2

    @Cleitonoliveira by the question he wants to know only different balances, so there should be accounts in only one of the tables, but I edited the answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.