我有两张桌子
Table A
有三列:AID, first name, surname
Tabel B
有四列:BID, AID, Address, TypeOFAddress
表A中的每个人在表B中各有四行。
Table_A
_AID_|_FIRST_|_LAST_
1 | Leo | White
2 | Joe | Black
Table_B
_BID_|_AID_|_ADDRESS_|_TYPE_
10 | 1 |Street 1 |STREET
11 | 1 |23490878 |ZIPCODE
12 | 1 |Town 1 |CITY
13 | 1 |Street 2 |STREET
14 | 1 |83083099 |ZIPCODE
15 | 1 |Town 2 |CITY
我想在一行中选择这些行,因此结果输出为
Result output
1 |Leo |White |Street 1 |23490878 |Town
2 |Joe |Black |Street 2 |83083099 |Town 2
我如何以一种很好的方式做到这一点?
答案 0 :(得分:2)
首先,JOIN
表。然后使用case
表达式进行条件聚合:
select t1.AID, t1.FIRST, t1.LAST,
max(case when t2.TypeOFAddress = 'STREET' then t2.Address end) STREET,
max(case when t2.TypeOFAddress = 'ZIPCODE' then t2.Address end) ZIPCODE,
max(case when t2.TypeOFAddress = 'CITY' then t2.Address end) CITY
from table1 t1
left join table2 t2 on t1.AID = t2.AID_
group by t1.AID, t1.FIRST, t1.LAST
答案 1 :(得分:1)
如果您使用的是Microsoft SQL Server,则可以使用PIVOT
SELECT * FROM
( SELECT A.*, B.ADDRESS, B.TYPE
FROM Table_A A
INNER JOIN Table_B B ON A.AID = B.AID
) SRC
PIVOT (MAX([ADDRESS]) FOR TYPE IN ([STREET],[ZIPCODE],[CITY])) PVT