0

我需要在一个临时表中显示一个用户该用户的多个电话,但我被困在选择中,我需要这样的东西:

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'

提前致谢。

4

1 回答 1

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 小提琴:http ://sqlfiddle.com/#!3/496f6/1

于 2012-07-13T20:55:41.440 回答