Say I have two tables named Customers and Banks.
- Customers has Id(PK), Name and BankCode
- Banks has Id(PK), Name and Code
BankCode column in Customers table is a loose reference to Code column in Banks table. Code is not a foreign key so there are multiple records with the same Code. Sample data is like this:
Persons:
Id | Name | BankCode |
---|---|---|
1 | Jack | 2 |
2 | Jane | 2 |
3 | John | 5 |
Banks:
Id | Name | Code |
---|---|---|
1 | National | 2 |
2 | National Subsidiary | 2 |
3 | GNB | 3 |
4 | Global Banking | 5 |
I need to get a list of persons with their bank name attached, I tried simply joining tables like this:
SELECT P.Id, P.Name, P.BankCode, B.Name
FROM Persons P
JOIN Banks B
ON P.BankCode = B.Code
But this query results in redundant records for persons whose bank code isn't unique. In this case Jack and Jane will each have two similar records with different bank names.
Since the banks with the same code are a family and have similar names, how can I manipulate the query to result only one record for each person (only use one bank name and ignore others)?