2013-08-29 8 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 ОТНОСИТЬСЯ, чтобы получить результат:

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 
Смежные вопросы