querying for duplicates in 2 tables SQL server

icnyk63a  于 2023-04-28  发布在  SQL Server
关注(0)|答案(2)|浏览(113)

I have a table table1 containing only the duplicate person_number and its corresponding account_number . How do I query for these duplicate person_number from main table master_table which has no person_number column but only the account_number column?

table1
person_numberaccount_number
111
122
133
144
155
master_table
account_numberaccount_balance
1238989
24889895
368897
4298729
5387745
6354655
7553455
835545

I would like to filter the master_table to only contain the account_number present in table1

resultant_table_of_duplicates
account_numberaccount_balance
1238989
24889895
368897
4298729
5387745
r3i60tvu

r3i60tvu1#

As already pointed in the comments section, one idea to carry out this task is using the EXISTS operator inside the WHERE clause, by checking all records from mastertable whose "account_number" can be found inside table1.

SELECT * 
FROM mastertable m
WHERE EXISTS(SELECT 1 
             FROM table1 t 
             WHERE m.account_number = t.account_number)

Output:

account_numberaccount_balance
1238989
24889895
368897
4298729
5387745

Check the demo here .

h6my8fg2

h6my8fg22#

select a.account_number,sum(account_balance) from master_table a
inner join table1 b on a.account_number=b.account_number
group by a.account_number

You can insert Base data with the following statements:

drop table if exists table1
create table table1(person_number int,  account_number int)

insert into     table1(person_number,account_number)  values(11 ,1)
insert into     table1(person_number,account_number)  values(12 ,2)
insert into     table1(person_number,account_number)  values(13 ,3)
insert into     table1(person_number,account_number)  values(14 ,4)
insert into     table1(person_number,account_number)  values(15 ,5)
drop table if exists master_table
create table master_table(account_number int,   account_balance int)

insert into     master_table( account_number,   account_balance)values(1,   238989    )
insert into     master_table( account_number,   account_balance)values(2,   4889895   )
insert into     master_table( account_number,   account_balance)values(3,   68897     )
insert into     master_table( account_number,   account_balance)values(4,   298729    )
insert into     master_table( account_number,   account_balance)values(5,   387745    )
insert into     master_table( account_number,   account_balance)values(6,   354655    )
insert into     master_table( account_number,   account_balance)values(7,   553455    )
insert into     master_table( account_number,   account_balance)values(8,   35545     )

相关问题