在为以下场景创建SQL时,我陷入困境

时间:2013-12-21 06:16:39

标签: sql toad

enter image description here

我尝试使用Case-End但没有任何效果。

电话号码的差异类型为:

  1. 主页
  2. 细胞
  3. 主要
  4. OTPR
  5. BUSN

3 个答案:

答案 0 :(得分: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;

您不能在一个字段中混合字符和数字,如果您在输出中需要n / a,则需要另一个步骤,使电话号码列为字符。

答案 1 :(得分: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

答案 2 :(得分:-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)