2016-08-21 27 views
1

我有這樣如何逆轉置不同的數據類型的SQL Server列

SELECT 
    totalvolume = SUM(volume), 
    totalusage = SUM(usage), 
    percentage = CAST(SUM(usage) * 100/SUM(volume) as decimal (10,2)), 
    YEAR 
FROM 
    table1 

查詢和我的表像下面

|totalvolume|totalusage|percentage|Year 
|-------------------------------------- 
| 100  | 50  | 50.00 |2016 
| 200  | 50  | 25.00 |2015 

我的目標是使名單表是這樣這種使用PIVOT

|Type  |2015 |2016 | 
|------------------------ | 
| totalvolume| 200 | 100 | 
| totalusage | 50 | 50 | 
| percentage |25.00|50.00 | 

所以我決定先創建該表使用)UNPIVOT

Type  | Value | year 
------------------- 
totalvolume |100 |2016 
totalusage |50  |2016 
percentage |50.00 |2016 
totalvolume |200 |2015 
totalusage |50  |2015 
percentage |25.00 |2015 

但在我UNPIVOT查詢

SELECT 
    Type, Value, Year 
FROM 
    <my table query> 
UNPIVOT 
    (value FOR Type IN (totalvolume, totalusage, percentage)) 

有一個在我的SQL錯誤:

的類型與其他列中指定的類型列「百分比」衝突UNPIVOT list

那麼有什麼解決方案可以解決解決這個問題而不改變數據類型?

如果我排除百分比列,因此它是這樣

|Type  |2015 |2016 | 
|------------------------ | 
| totalvolume| 200 | 100 | 
| totalusage | 50 | 50 | 

但我需要的百分比排,我也能拿我想用樞軸視圖。

在此先感謝

+0

旋轉和格式(即「百分比」)都是報告工具函數,而不是數據庫函數。你對這些數據做了什麼?將它作爲報告發送?使用報告工具。 –

回答

0

沒有辦法在一列中有不同的數據類型。但是你可以通過所有的值轉換爲VARCHAR像下面

SELECT 
    Type, Value, Year 
FROM 
    (select 
     convert(varchar(100), totalvolume) as totalvolume, 
     convert(varchar(100), totalusage) as totalusage, 
     convert(varchar(100), percentage) as totalusage 
     from <my table query>) pv 
UNPIVOT 
    (value FOR Type IN (totalvolume, totalusage, percentage)) unp 

然後,如果你需要做一些計算,你將不得不做反向轉換模擬。

+0

所以基本上我需要轉換爲varchar來獲取unpivot表,然後再次將其轉換爲最終的數據透視表? –

+0

只有當您計劃進行一些計算時,您才需要再次進行轉換,例如MAX,MIN,AVG,SUM等。如果您只需顯示輸出,則無需將其轉換回原始數據類型。 – Anton

+0

例如,如果你需要找到總體積,你應該做一些像SELECT SUM(CONVERT(int,Value))FROM unpivot_table WHERE Type ='totalvolume' – Anton

0

在這種情況下,您可以將轉換操作轉換爲常用數字格式,然後格式化最終輸出的選項。

with data(totalvolume, totalusage, percentage, Year) as (
    select 100, 50, 50.00, 2016 union all 
    select 200, 50, 25.00, 2015 
), converted(totalvolume, totalusage, percentage, Year) as (
    select 
     cast(totalvolume as decimal(8, 2)), 
     cast(totalusage as decimal(8, 2)), 
     cast(percentage as decimal(8, 2)), 
     cast(Year as decimal(8, 2)) 
    from data 
) 
select 
    Type, 
    case 
     when Type in ('totalvolume', 'totalusage') then format(Value, '0') 
     when Type = 'percentage' then format(Value, '0.00\%') 
    end as Value, 
    format(Year, '0') as Year 
from converted unpivot 
    (value for Type int (totalvolume, totalusage, percentage)) as unpvt 
order by 
    Year, Type desc;