2012-07-13 16 views
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' 

在此先感謝。

+0

** clients_has_phones **表是什麼樣子的? – Brad 2012-07-13 17:40:19

+0

顯示錶結構 – Samson 2012-07-13 18:08:52

+0

是一個包含有關客戶端信息的表,並且具有諸如名稱,地址等行。但在臨時表中,我只需要該用戶的用戶名和所有電話號碼,這要提前感謝。 – suely 2012-07-13 18:09:44

回答

1

我想不出做比自加入關於手機如何以往任何時候都多的數字用戶可能有..有了這樣說,你可以試試這個爲你的SELECT語句其他select語句的一個好辦法:

;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

+0

謝謝我會嘗試此代碼,我會讓你知道。 – suely 2012-07-13 20:57:39

+0

它可能工作..但你需要知道每個人有多少電話。搜索出現時通常使用自連接。 – Samson 2012-07-13 23:38:27

相關問題