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
既然你想旋转多列的数据,我会首先build议unpivoting的result
, score
和grade
列,所以你没有多个列,但你会有多行。
根据您的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小提琴 。 一旦数据已经转换,那么你可以应用PIVOTfunction:
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小提琴 。 这会给你结果:
| 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 |