我是sql的新手。 我有这些表:
表格个人:
IndividualId IndividualName
Ind1 Mark
Ind2 Paul
ind3 Spencer
ind4 Mike
ind5 Hilary
表代理:
AgentId IndId(foreignKey)
Agent1 ind1
Agent1 ind2
Agent2 ind1
Agent3 ind4
交易表(交易可以通过代理商或个人自己进行):
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
结果应该是:(如果交易与代理关联,则显示在同一行,否则显示在单独的行上)
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
根据一些评论,我使用了以下查询:
SELECT DISTINCT IndividualId, IndividualName, TranId, Agent.AgentId, Amount
FROM Individual
LEFT JOIN Transactions
ON Individual.IndividualId = Transactions.IndId
LEFT JOIN Agent
ON Transactions.AgentId = Agent.AgentId
这给出了以下不正确的结果:
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
答案 0 :(得分:1)
试试这个:
SELECT Distinct IndividualId, IndividualName, Agent.AgentId, TranId, Amount
FROM Individual
Left join Agent ON Individual.IndividualId = Agent.IndId
left join Transactions
on Individual.IndividualId = Transactions.IndId and Transactions.AgentId = Agent.AgentId
union
SELECT Distinct IndividualId, Name, TranId,NUll as AgentId, Amount
FROM Individual
left join Transactions
on Individual.IndividualId = Transactions.IndId and Transactions.AgentId is null