sql查询来组合来自同一个表的结果

时间:2012-10-02 09:49:51

标签: sql sql-server

我有桌子客户(id,名称)电话(id,customerId,phoneType,phone) 是否可以编写一个返回如下行的查询:

CustomerId,CustomerName,Phone1,Phone2,Mobile1,Mobile2

Phone1,Phone2,Mobile1,Mobile2是手机类型

我试过

select id as CustomerId, name as CustomerName, phone as Phone1
from Customers, Phones
where Customers.id = Phones.customerId and 
Phones.phoneType = N'Phone1'

1 个答案:

答案 0 :(得分:1)

使用pivot

select *
from (select id as customerid, name as customername, phonetype, phone
     from customers inner join phones on customers.id = phones.customerid
) src
pivot
(max(phone) for phonetype in ([phone1],[phone2],[mobile1],[mobile2])) p