2013-08-29 69 views
1

我在那裏的數據將顯示這樣一個表中的數據:如何列轉換爲行

DatePeriod Good Fair Poor NotCategorised NotTested GoodPercentage FairPercentage PoorPercentage NotCategorisedPercentage NotTestedPercentage 
Feb-13 4 0 0 0 60 6.25 0 0 0 93.75 

而對於這一次我已經使用UNPIVOT書面查詢。

Select DatePeriod,Legend FROM 
(
select DatePeriod,Good,Fair,Poor,NotCategorised,NotTested,GoodPercentage, 
FairPercentage,poorPercentage,NotCategorisedPercentage,NotTestedPercentage from #cte 

)P 
UNPIVOT(Legend FOR #CTE IN (Good,Fair,Poor,NotCategorised,NotTested))AS UNPVT; 

我沒有得到所需要的輸出

我的結果集必須這樣的:

year Legend percent count 
Dec-12 Good 13.89 35 
Dec-12 Fair 0 0 
Dec-12 Poor 0 0 
Dec-12 NC 0 0 
Dec-12 NoData 86.11 217 

我建議最好的方式。

+0

它有助於提供表定義,和你實際看到的結果。我們輸入的越少,爲了測試更快,您將得到答案。 – BlackICE

回答

2

您沒有指定您正在使用的SQL Server版本,但對於您的數據使用UNPIVOT可能會更困難,因爲您想要取消轉移集合中的列。這可能是更容易使用CROSS APPLY來得到結果:

select dateperiod, 
    Legend, 
    [Percent], 
    [Count] 
from yourtable t 
cross apply 
(
    select 'Good', Good, GoodPercentage union all 
    select 'Fair', Fair, FairPercentage union all 
    select 'Poor', Poor, PoorPercentage union all 
    select 'NotCategorised', NotCategorised, NotCategorisedPercentage union all 
    select 'NotTested', NotTested, NotTestedPercentage 
) c (Legend, [Percent], [Count]); 

SQL Fiddle with Demo。如果您使用的是SQL Server版本支持VALUES子句,那麼你可以改變上面的以下內容:

select dateperiod, 
    Legend, 
    [Percent], 
    [Count] 
from yourtable t 
cross apply 
(
    values 
    ('Good', Good, GoodPercentage), 
    ('Fair', Fair, FairPercentage), 
    ('Poor', Poor, PoorPercentage), 
    ('NotCategorised', NotCategorised, NotCategorisedPercentage), 
    ('NotTested', NotTested, NotTestedPercentage) 
) c (Legend, [Percent], [Count]); 

SQL Fiddle with Demo。這些給出了結果:

| DATEPERIOD |   LEGEND | PERCENT | COUNT | 
|  Feb-13 |   Good |  4 | 6.25 | 
|  Feb-13 |   Fair |  0 |  0 | 
|  Feb-13 |   Poor |  0 |  0 | 
|  Feb-13 | NotCategorised |  0 |  0 | 
|  Feb-13 |  NotTested |  60 | 93.75 | 
1

你可以unpivot兩次。

Select 
    DatePeriod, 
    Legend, 
    amount, 
    pc  
FROM 
(
select DatePeriod, 
Good,Fair,Poor,NotCategorised,NotTested,GoodPercentage, 
FairPercentage,poorPercentage,NotCategorisedPercentage,NotTestedPercentage 
from yourtable  
)P 
UNPIVOT(Amount FOR Legend IN (Good,Fair,Poor,NotCategorised,NotTested))AS UNPVT 
unpivot(pc for var in (GoodPercentage, FairPercentage, PoorPercentage, NotCategorisedPercentage,NotTestedPercentage)) u2 
where REPLACE(var,'Percentage','')=Legend 

或者,如果因爲它似乎你的數據包含冗餘的信息,請百分比計算

Select 
    DatePeriod, 
    Legend, 
    amount, 
    100.0*Amount/nullif(SUM(Amount) over (partition by dateperiod),0) 

FROM 
(
select DatePeriod, 
Good,Fair,Poor,NotCategorised,NotTested,GoodPercentage, 
FairPercentage,poorPercentage,NotCategorisedPercentage,NotTestedPercentage from @t 

)P 
UNPIVOT(Amount FOR Legend IN (Good,Fair,Poor,NotCategorised,NotTested))AS UNPVT