【问题标题】:one user many phones in a temp table一个用户在一张临时表中有很多电话
【发布时间】:2012-07-13 17:19:23
【问题描述】:

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

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'

提前致谢。

【问题讨论】:

  • clients_has_phones 表是什么样的?
  • 显示表结构
  • 是一个包含客户信息的表格,其中包含名称、地址等行。但在临时表中,我只需要那个人的用户 ID 和所有电话号码,提前谢谢。
  • @suely 我们需要实际的表模式 ex。每行只有1个电话号码吗?是否有多行 user_number 相同?等等。如果您可以编辑您的问题以显示表格示例(以便我们可以复制表格)以帮助找出您的问题,这将有所帮助。
  • 这是您想要达到的目标吗? stackoverflow.com/questions/273238/…

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


【解决方案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

【讨论】:

  • 它可能有效..但您需要知道每部手机有多少部。搜索出现时通常使用自连接。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-08
  • 1970-01-01
  • 2017-04-20
  • 1970-01-01
相关资源
最近更新 更多