一个用户在临时表中有很多电话

时间:2012-07-13 17:19:23

标签: sql-server sql-server-2008 select one-to-many

我需要在临时表中向一位用户显示该用户的许多电话,但我被卡住了   在选择中,我需要这样的东西:

user1        phone1   phone2    phone3   phone4  phone5
11816116-5   8555588  77877888  33254477 224474  45777885

这是我正在尝试的代码:

select
    phone As phonenum 
Into #Tmp_phonenumber 
From 
    clients_has_phones 
where 
    user_number='11816116-5'

提前感谢。

1 个答案:

答案 0 :(得分:1)

除了通过自我加入你的用户可能拥有多少个电话号码之外,我想不出一个做选择语句的好方法。据说你可以尝试这个用于你的选择语句:

;With CTE_Main as (
Select
  id
  ,Fono
  ,row_number()
    Over(Partition by ID order by Fono) as RN
From sucursales
), CTE_Users as (
Select
  id as id_num
  from sucursales
  group by id
)
Select
  id_num
  ,a.Fono as Phone_1
  ,b.Fono as Phone_2
  ,c.Fono as Phone_3
  ,d.Fono as Phone_4
  ,e.Fono as Phone_5
From CTE_Users as realz
  Left Join [CTE_Main] as a on a.id = realz.id_num and a.RN = 1
  Left Join [CTE_Main] as b on b.id = realz.id_num and b.RN = 2
  Left Join [CTE_Main] as c on c.id = realz.id_num and c.RN = 3
  Left Join [CTE_Main] as d on d.id = realz.id_num and d.RN = 4
  Left Join [CTE_Main] as e on e.id = realz.id_num and e.RN = 5

我知道它有点冗长,但它会以你想要的方式显示结果。我的例子只使用了5行,但它应该是非常自我解释的。

Sql Fiddle:http://sqlfiddle.com/#!3/496f6/1