2014-10-02 36 views
0

我有這樣一個表:樞軸電話號碼到電話1,電話2等的SQL Server中的表

PhoneId CustId  PhoneNum  Ext 
    1  1  234-243-2345 100 
    2  1  234-234-2456 101 
    3  1  234-245-3253 NULL 
    4  2  243-434-3553 NULL 
    5  3  424-242-4242 NULL 
    6  3  123-123-2322 333 
    ... 

如何編寫一個查詢返回類似結果:

CustId Phone1   Ext1 Phone2   Ext2 Phone3   Ext3 
    1  234-243-2345 100 234-234-2456 101  234-245-3253 NULL 
    2  243-434-3553 NULL NULL   NULL NULL   NULL 
    3  424-242-4242 NULL 123-123-2322 333  NULL   NULL 

回答

1
select custId, 
max(case when T.seq =1 then T.PhoneNum end) as 'Phone1', 
max(case when T.seq =1 then T.Ext end) as 'Ext1', 
max(case when T.seq =2 then T.PhoneNum end) as 'Phone2', 
max(case when T.seq =2 then T.Ext end) as 'Ext2', 
max(case when T.seq =3 then T.PhoneNum end) as 'Phone3', 
max(case when T.seq =3 then T.Ext end) as 'Ext3' 
FROM 
(select ROW_NUMBER() over (partition by custId order by (select null)) as seq, * from Table1) T 
group by custId 
1

這裏是做的另一種方法:

看到這裏演示 http://sqlfiddle.com/#!6/809b1/1

Select * 
From (
Select CustId, value,col+'_'+ 
    cast(Row_Number()Over(Partition By custId, col Order by PhoneId) as nvarchar) col 
From yourtable 
Cross Apply 
(
select PhoneNum, 'Phone' union all 
select Ext, 'Ext' 
) c(value, col) 
) X Pivot(max(Value) for 
      col in ([Phone_1],[Ext_1],[Phone_2],[Ext_2],[Phone_3],[Ext_3])) pvt