2013-10-25 128 views
30

我有下面的表格,但不確定是否有可能轉動它並保留所有標籤。TSQL樞軸多列

RATIO    RESULT SCORE GRADE 
Current Ratio  1.294 60  Good 
Gearing Ratio  0.3384 70  Good 
Performance Ratio 0.0427 50  Satisfactory 
TOTAL    NULL 180  Good 

我會承認自己不是很好的使用樞軸,所以導致這個輸出經過幾次嘗試:

SELECT 'RESULT' AS 'Ratio' 
    ,[Current Ratio] AS 'Current Ratio' 
    ,[Gearing Ratio] AS 'Gearing Ratio' 
    ,[Performance Ratio] AS 'Performance Ratio' 
    ,[TOTAL] AS 'TOTAL' 
FROM 
(
    SELECT RATIO, RESULT 
    FROM GRAND_TOTALS 
) AS SREC 
PIVOT 
(
    MAX(RESULT) 
    FOR RATIO IN ([Current Ratio],[Gearing Ratio], [Performance Ratio], [TOTAL]) 
) AS PVT 

這給出結果:

Ratio Current Ratio Gearing Ratio Performance Ratio 
Result 1.294  0.3384  0.0427 

我會承認感到非常難以接受下一步做什麼以產生我需要的結果:

Ratio Current Ratio Gearing Ratio Performance Ratio TOTAL 
Result  1.294  0.3384    0.0427   NULL 
Score  60    70    50    180 
Grade  Good   Good   Satisfactory   Good 
+0

你使用的是什麼版本的sql server? – Taryn

+0

[T-SQL中的Multiple Column Pivot]的可能的重複(http://stackoverflow.com/questions/947281/multiple-column-pivot-in-t-sql) –

回答

39

由於您要旋轉多列數據,因此我會首先建議您將不透明的列設置爲result,scoregrade,以便您沒有多列,但是將有多行。

根據您的SQL Server版本,您可以使用UNPIVOT函數或CROSS APPLY。未反轉數據的語法將類似於:

select ratio, col, value 
from GRAND_TOTALS 
cross apply 
(
    select 'result', cast(result as varchar(10)) union all 
    select 'score', cast(score as varchar(10)) union all 
    select 'grade', grade 
) c(col, value) 

請參閱SQL Fiddle with Demo。一旦數據已經unpivot操作,那麼您可以將旋轉功能:

select ratio = col, 
    [current ratio], [gearing ratio], [performance ratio], total 
from 
(
    select ratio, col, value 
    from GRAND_TOTALS 
    cross apply 
    (
    select 'result', cast(result as varchar(10)) union all 
    select 'score', cast(score as varchar(10)) union all 
    select 'grade', grade 
) c(col, value) 
) d 
pivot 
(
    max(value) 
    for ratio in ([current ratio], [gearing ratio], [performance ratio], total) 
) piv; 

SQL Fiddle with Demo。這會給你結果:

| RATIO | CURRENT RATIO | GEARING RATIO | PERFORMANCE RATIO |  TOTAL | 
|--------|---------------|---------------|-------------------|-----------| 
| grade |   Good |   Good |  Satisfactory |  Good | 
| result |  1.29400 |  0.33840 |   0.04270 | (null) | 
| score |  60.00000 |  70.00000 |   50.00000 | 180.00000 | 
+1

我會通過PIVOT真正的解決方案留下深刻的印象專家!我在這裏找到了這個:http://pratchev.blogspot.de/2009/01/pivoting-on-multiple-columns.html。在第二章中,作者在一個聲明中提出了兩個PIVOT子句。這是否有缺點? –

+0

@DerU它真的取決於,我個人更喜歡unpivot,所以數據更容易格式,然後應用兩個樞軸。 – Taryn