2013-12-21 224 views

回答

1
select emplid, 
max(case when phone_type='home' then phone_number else -1 end) Home, 
max(case when phone_type='cell' then phone_number else -1 end) Cell, 
..... 
from phone_data 
group by emplid; 

您不能混用字符和NU meric在一個字段中,如果您在輸出中需要n/a,則需要使電話號碼列字符變爲另一個步驟。

+0

上面的代碼不工作,返回-1(N/A - 爲電話號碼數據類型是字符,在實際情況下)在每種情況下。而不是返回電話號碼。 –

-1

試試這個SQL查詢!

DECLARE @cols AS NVARCHAR(MAX),@query AS NVARCHAR(MAX); 

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.phone_type) 
      FROM youtablename c 
      FOR XML PATH(''), TYPE 
      ).value('.', 'NVARCHAR(MAX)') 
     ,1,1,'') 

set @query = 'SELECT empid, ' + @cols + ' from 
      (
       select empid 
        , phone_number 
        , phone_type 
       from youtablename 
      ) x 
      pivot 
      (
       max(phone_number) 
       for phone_type in (' + @cols + ') 
      ) p ' 

execute(@query) 
0
select t.empid as empid, cell.phone_number as cell, home.phone_number as Home 
from telephones t 
inner join telephones cell on t.empid = cell.empid 
inner join telephones home on t.empid = home.empid 
where cell.Phone_type = "cell" 
and home.Phone_type = "home" 
group by t.empid 

和一個SQL小提琴:http://sqlfiddle.com/#!2/6bb17/11

+0

僅爲擁有phone_type即Cell和Home的員工返回一組數據。在任何情況下,一個人只有一個phone_type然後不會返回該特定的行。 –