我有一张表A如下:
ID Name Age
1 A 18
2 B 19
此表与地址表具有一对多的映射。
ID ParentID AddressType ALine1 ALine2 State City Country
10 1 Mail AAA AAA AAB CCC CDCD
11 1 Home BBB BBA BAB CAC CFCF
12 2 Mail CAV VAC CSC DFS DDDC
我需要获得所需的输出:
Name Age Address1Type ALine1 ALine2 State1 City1 Country1 Address2Type A2Line1 A2Line2 State2 City2 Country2
---- --- ------------ ------ ------ ------ ----- -------- ------------ ------- -------- ------ ----- --------
A 18 Mail AAA AAA AAB CCC CDCD Home BBB BBA BAB CAC CFCF
B 19 Mail CAV VAC CSC DFS DDDC null null null null null null
我可以将它们组合在一起,但可以获得同名的多个记录。如何获得我需要的输出?
答案 0 :(得分:0)
试试这个:
SELECT parent.Name,
parent.Age,
mailInfo.*,
homeInfo.*
FROM parent
LEFT OUTER JOIN addresses AS mailInfo
ON parent.ID = mailInfo.ParentID
AND mailInfo.AddressType = 'Mail'
LEFT OUTER JOIN addresses AS homeInfo
ON parent.ID = homeInfo.ParentID
AND mailInfo.AddressType = 'Home';