2016-07-26 87 views
1

我有一個表我使用PIVOT,它的工作原理和正確返回數據透視列的數據,但我有我想要的行中的其他列綁定到樞軸柱。SQL在一列選擇PIVOT,但選擇其他列連接到樞軸字段

例子:

ID, PhoneType (column to PIVOT), PhoneNumber (value to be pivoted), PhoneAttribute1, PhoneAttribute2, PhoneAttribute3. 

1, Cell, 123456789, call, dontcall, pleasecall 
1, work, 123456780, call2, dontcall2, pleasecall2 
2, Home, 123456782, call2, dontcall2, pleasecall2 

當我透視數據(無屬性列),我得到的輸出:

ID, CELL, Work, Home 
1, 123456789, 123456780, NULL 
2, NULL, NULL, 123456782 

哪個是正確的,但我想其他attributcolumns添加到該列表使其將每個屬性與每個電話號碼綁定,如下所示:

ID, CELL, Work, Home, CELLPhoneAttribute1, CELLPhoneAttribute2, CELLPhoneAttribute3, WorkPhoneAttribute1, WorkPhoneAttribute2, WorkPhoneAttribute3,...... 

這可能嗎?

我可以用連接來做,但這可能很麻煩,如果我添加更多的phonetypes,它會變得更大。

有什麼建議嗎?

回答

0

據我所知,這是不可能的,沒有使用幾個常規的連接。

生成的數據表的預期用途是什麼?大多數報告工具可讓您輕鬆進行此分組。例如,在表格矩陣中將SSRS內的行級別和列級別組合在一起。

+0

我需要使用數據作爲過程的一部分來運行過濾器和其他操作。所以一個基本的報告不會爲這些目的而工作 – Brad

+0

我認爲,如果您可以告訴我們更多關於該過程的信息,可以找到更好的解決方案。一般來說,試圖在SQL中做你正在做的事情很少是最好的方法,通常可以不做,通過改變你的方法來完成整個任務。 – iamdave

1

您也可以使用條件聚合。在這種情況下,不需要連接。不是最漂亮的,但也不難擴展。

select id, 
     max(case when phone_type = 'Cell' then PhoneNumber end) as CELL, 
     max(case when phone_type = 'work' then PhoneNumber end) as Work, 
     max(case when phone_type = 'Home' then PhoneNumber end) as Home, 
     max(case when phone_type = 'Cell' then PhoneAttribute1 end) as CELLPhoneAttribute1, 
     max(case when phone_type = 'Cell' then PhoneAttribute2 end) as CELLPhoneAttribute2, 
     max(case when phone_type = 'Cell' then PhoneAttribute3 end) as CELLPhoneAttribute3, 
     max(case when phone_type = 'work' then PhoneAttribute1 end) as WorkPhoneAttribute1, 
     max(case when phone_type = 'work' then PhoneAttribute2 end) as WorkPhoneAttribute2, 
     max(case when phone_type = 'work' then PhoneAttribute3 end) as WorkPhoneAttribute3, 
     max(case when phone_type = 'Home' then PhoneAttribute1 end) as HomePhoneAttribute1, 
     max(case when phone_type = 'Home' then PhoneAttribute2 end) as HomePhoneAttribute2, 
     max(case when phone_type = 'Home' then PhoneAttribute3 end) as HomePhoneAttribute3 
    from tbl 
group by id