2013-10-25 103 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