sql server - Stuck with sql joins -
i newbie sql. have these tables:
table individual:
individualid individualname ind1 mark ind2 paul ind3 spencer ind4 mike ind5 hilary
table agent:
agentid indid(foreignkey) agent1 ind1 agent1 ind2 agent2 ind1 agent3 ind4
transaction table (transaction can made via agent or individual himself):
tranid indid(foreignkey/never null) agentid(foreignkey) tranamount tran1 ind1 agent1 $100 tran2 ind1 null $500 tran3 ind3 null $200 tran4 ind4 agent3 $50 tran5 ind4 null $30
result should like: (if transaction associated agent, display in same line else display on separate line)
individualid individualname agentid tranid tranamount ind1 mark agent1 tran1 $100 ind1 mark agent2 null null ind1 mark null tran2 $500 ind2 paul agent1 null null ind3 spencer null tran3 $200 ind4 mike agent3 tran4 $50 ind4 mike null tran5 $30 ind5 hilary null null null
as per comments, used following query:
select distinct individualid, individualname, tranid, agent.agentid, amount individual left join transactions on individual.individualid = transactions.indid left join agent on transactions.agentid = agent.agentid
which gave below results not correct:
individualid individualname tranid agentid amount ind1 mark tran1 agent1 100 ind1 mark tran2 null 500 ind2 paul null null null ind3 spencer tran3 null 200 ind4 mike tran4 agent3 50 ind4 mike tran5 null 30 ind5 hilary null null null
try this:
select distinct individualid, individualname, agent.agentid, tranid, amount individual left join agent on individual.individualid = agent.indid left join transactions on individual.individualid = transactions.indid , transactions.agentid = agent.agentid union select distinct individualid, name, tranid,null agentid, amount individual left join transactions on individual.individualid = transactions.indid , transactions.agentid null
Comments
Post a Comment