Given the following (heavily simplified) tables:
create table Tags (
TagId int Primary Key
)
create table OrderLines (
Branch int,
Station int,
TransNo int,
TagId int foreign key references Tags,
primary key (Branch, Station, TransNo)
)
I need a list of Tags along with an OrderLine which references each Tag. I am expecting zero or one OrderLines to reference each Tag, but there is nothing in the database constraints to enforce this.
Given input like this:
OrderLines Tags
Branch Station TransNo TagId TagId
1 100 2345 1 1
1 100 2346 1 2
1 101 5223 2 3
3 100 6677 4 4
I want to get output like this:
TagId Branch Station TransNo
1 1 100 2345 <-- it could list 2346 here, don't care
2 1 101 5223
3 null null null
4 3 100 6677
Note that although TagId 1 is referenced twice, my output only contains one of it. It doesn't matter which OrderLine is listed alongside it, but there must be only one instance of each tag in the output.
What is the most efficient way to do this?
I'm not able to alter the database schema.