根据值拆分列

时间:2019-01-17 07:35:33

标签: sql sql-server

根据下表将一列分为不同的列

Phone type
    ptype_id|description
    1      HOME
    2      WORK
    3      CELL

Phone 
phoID|pho_PhoneNum|ptype_id
1        012313       1
2        0132465      2
3        1324654      3
....

根据上表,输出应在其自己的列中显示单元,家,工作 如

 phoID|Home|Work|Cell
   1   null|null|124
   2   null|156 |null
   3   789 |null|null

任何建议或指导将不胜感激

我试图隔离工作类型的内容。但它返回null作为工作 但是phoID中有值

   Select  pho.phoId, 
    (Select pho2.pho_phoneNum from Phone pho2 
     join PhoneType pht2 
     on pho2.ptypeid=pht2.ptypeid  
      And pht2.description='Work'
      And pht2.ptypeid=2 
     Where pho2.ptypeid=pho.ptypeid  
      And pho.ptypeid=2) as Work
     from Phone pho;

3 个答案:

答案 0 :(得分:1)

select phoID,
       case when ptype_id = 1 then pho_PhoneNum else NULL end as Home,
       case when ptype_id = 2 then pho_PhoneNum else NULL end as Work,
       case when ptype_id = 3 then pho_PhoneNum else NULL end as Cell
from phone

答案 1 :(得分:1)

使用条件聚合并联接两个表

select phoID, max(case when ptype_id = 1 then pho_PhoneNum end) as Home,
       max(case when ptype_id = 2 then pho_PhoneNum  end) as Work,
      max( case when ptype_id = 3 then pho_PhoneNum  end) as Cell
     from phone p join phoneType pt
    on p.ptype_id=pt.ptype_id
    group by phoID

答案 2 :(得分:1)

样本数据

CREATE table #Phonetype
( ptype_id INT,
 description VARCHAR(20)
 )
 INSERT INTO   #Phonetype
 SELECT 1,'HOME' UNION ALL
 SELECT 2,'WORK' UNION ALL
 SELECT 3,'CELL' 

CREATE table #Phone 
(phoID INT,
pho_PhoneNum BIGINT,
ptype_id INT)

INSERT INTO #Phone
SELECT 1,012313 ,1 UNION ALL
SELECT 2,0132465,2 UNION ALL
SELECT 3,1324654,3

在Sql服务器中使用PIVOT

DECLARE @Columns nvarchar(max),
        @IsnullColumns nvarchar(max),
        @Sql  nvarchar(max)


SELECT @Columns= STUFF((SELECT ', '+QUOTENAME([description]) FROM  #Phonetype t
INNER JOIN  #Phone  p
On t.ptype_id=p.ptype_id FOR XML PATH ('')),1,1,'')


SET @Sql='
SELECT [phoID], '+@Columns+'
FROM
    (   SELECT T.ptype_id, 
            [description],
            phoID,
            pho_PhoneNum
        FROM #Phonetype t
        INNER JOIN  #Phone  p
        On t.ptype_id=p.ptype_id

    ) AS SRC
 PIVOT 
   (MAX(pho_PhoneNum) FOR [description] IN('+@Columns+')
   ) AS PVT
'
PRINT @Sql
EXEC (@Sql)