我正在尝试创建一个SQL查询,该查询可以从一个表中选择多个条目并将它们输入到同一行的不同列中。
示例:
表1“人员”
|---------------------|------------------|------------------|
| PersonID | FirstName | LastName |
|---------------------|------------------|------------------|
| 1 | John | Smith |
|---------------------|------------------|------------------|
| 2 | Jane | Doe |
|---------------------|------------------|------------------|
表2“电话类型”
|---------------------|------------------|
| PhoneTypeID | Name |
|---------------------|------------------|
| 1 | Home |
|---------------------|------------------|
| 2 | Work |
|---------------------|------------------|
| 3 | Mobile |
|---------------------|------------------|
表3“电话号码”
|---------------------|------------------|------------------|
| PersonID | PhoneTypeID | PhoneNumber |
|---------------------|------------------|------------------|
| 1 | 1 | 12300 |
|---------------------|------------------|------------------|
| 2 | 1 | 45600 |
|---------------------|------------------|------------------|
| 2 | 2 | 78900 |
|---------------------|------------------|------------------|
SQL查询的预期结果:
|------------------|---------------|---------------|---------------|
| FirstName | LastName |HomePhoneNumber|WorkPhoneNumber|
|------------------|---------------|---------------|---------------|
| John | Smith | 12300 | NULL |
|------------------|---------------|---------------|---------------|
| Jane | Doe | 45600 | 78900 |
|------------------|---------------|---------------|---------------|
我想从表PhoneNumber中选择家庭和工作电话号码,并将它们写在同一行的不同列中。
查询应该看起来像这样:
SELECT Person.FirstName, Person.LastName, PhoneNumber.PhoneNumber AS HomePhoneNumber, PhoneNumber.PhoneNumber AS WorkPhoneNumber
FROM Person
LEFT OUTER JOIN PhoneNumber ON Person.PersonID = PhoneNumber.PersonID
LEFT OUTER JOIN PhoneType ON PhoneType.PhoneTypeID = PhoneNumber.PhoneTypeID
WHERE PhoneType.PhoneTypeID = 'Home'
OR PhoneType.PhoneTypeID = 'Work'
答案 0 :(得分:1)
您可以在连接子句中指定PhoneTypeID
SELECT Person.FirstName, Person.LastName, HomePhone.PhoneNumber AS HomePhoneNumber, WorkPhone.PhoneNumber AS WorkPhoneNumber
FROM Person
LEFT OUTER JOIN PhoneNumber HomePhone ON Person.PersonID = HomePhone.PersonID
and HomePhone.PhoneTypeID = 1
LEFT OUTER JOIN PhoneNumber WorkPhone ON Person.PersonID = WorkPhone.PersonID
and WorkPhone.PhoneTypeID = 2
答案 1 :(得分:0)
您可以将correlated subquery
用作
select FirstName,LastName,
( select PhoneNumber
from PhoneNumber
where PhoneTypeID = 1 and PersonID = p.PersonID ) as HomePhoneNumber,
( select PhoneNumber
from PhoneNumber
where PhoneTypeID = 2 and PersonID = p.PersonID ) as WorkPhoneNumber
from person p;
或将conditional aggregation
与left join
一起使用
select FirstName,LastName,
max( case when PhoneTypeID = 1 then n.PhoneNumber end ) as HomePhoneNumber,
max( case when PhoneTypeID = 2 then n.PhoneNumber end ) as WorkPhoneNumber
from person p
left join PhoneNumber n
on n.PersonID = p.PersonID
group by FirstName,LastName