2017-05-28 78 views
0

我有下表。讓我們叫它手機如何將行值轉換爲列

-------------------------- 
| userid | type | number | 
-------------------------- 
| 1  | home | 123456 | 
-------------------------- 
| 1  |office| 654321 | 
-------------------------- 

,所以我希望它是這樣的:

-------------------------- 
| userid | home | office | 
-------------------------- 
| 1  |123456| 654321 | 
-------------------------- 

我試圖透視表,但問題是,我沒有任何領域聚集。任何建議?

PS 我使用Azure的SQL服務器

+0

什麼是數據庫? –

+0

Azure SQL Server對不起,忘了指定 – Francis

回答

1

一種方法是:

with your_table(userid , type , number) as (
    select 1  ,'home','123456' union all 
    select 1  ,'office','654321' union all 
    select 2  ,'home','4444' union all 
    select 3  ,'office','77777' 
) 

-- below is actual query: 

select coalesce(t1.userid, t2.userid) as userid, t1.home, t2.office from 
(select userid, number as home from your_table where type = 'home') t1 
full join 
(select userid, number as office from your_table where type = 'office') t2 
on t1.userid = t2.userid 

如果您有其他價值觀也type列,並且您需要顯示他們爲列,那麼你應該加入另一個子查詢和full join也。

+0

哇。我剛試過你的查詢。認真的這節省了我非常多的謝謝 – Francis

+0

不客氣 –

0

的情況下,您不必重複值:

select 
    user_id, 
    min(case when type='home' then type else null end) home, 
    min(case when type='office' then type else null end) office 
from 
    phone 
group by 
    userid;