TSQL PIVOT MULTIPLE COLUMNS

Uch*_*lah 35 sql t-sql sql-server pivot

我有下表但不确定是否可以转动这个并保留所有标签.

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
Run Code Online (Sandbox Code Playgroud)

我承认在使用枢轴方面不是很好,所以经过几次尝试导致这个输出:

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
Run Code Online (Sandbox Code Playgroud)

这给出了结果:

Ratio    Current Ratio   Gearing Ratio   Performance Ratio
Result   1.294           0.3384          0.0427
Run Code Online (Sandbox Code Playgroud)

我承认我对接下来要做什么感到非常难过,以产生我需要的结果:

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
Run Code Online (Sandbox Code Playgroud)

Tar*_*ryn 47

由于您想要转移多列数据,我首先会建议对这些列和列进行取消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)
Run Code Online (Sandbox Code Playgroud)

请参阅SQL Fiddle with Demo.一旦数据被取消,您就可以应用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;
Run Code Online (Sandbox Code Playgroud)

请参阅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 |
Run Code Online (Sandbox Code Playgroud)

  • 对于真正专家的PIVOT解决方案,我总是会留下深刻的印象!我在这里找到了这个:http://pratchev.blogspot.de/2009/01/pivoting-on-multiple-columns.html.在第二段中,作者在一个陈述中提出了两个PIVOT条款.这有什么缺点吗? (4认同)