繁体   English   中英

TSQL PIVOT多列

[英]TSQL PIVOT MULTIPLE COLUMNS

我有下表,但不确定是否可以旋转它并保留所有标签。

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

由于您想透视数据的多列,因此我首先建议不要透视resultscoregrade列,这样就不会有多列,但会有多行。

根据您的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 一旦数据被取消透视,就可以应用PIVOT功能:

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 这将为您提供结果:

|  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 |

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM