【问题标题】:TSQL PIVOT MULTIPLE COLUMNSTSQL PIVOT 多列
【发布时间】:2013-11-04 15:04:43
【问题描述】:

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

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

【问题讨论】:

标签: sql sql-server tsql pivot


【解决方案1】:

由于您要旋转多列数据,我首先建议取消旋转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 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;

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 |

【讨论】:

  • 真正专家的 PIVOT 解决方案总会给我留下深刻印象!我在这里找到了这个:pratchev.blogspot.de/2009/01/pivoting-on-multiple-columns.html。在第二段中,作者在一个语句中建议了两个 PIVOT 子句。这有缺点吗?
  • @DerU 这真的取决于,我个人更喜欢 unpivot,这样数据的格式比应用两个枢轴更简单。
  • @DerU - 我非常喜欢您所附文章中的方法。我也在同一条船上 Taryn,因为它确实取决于。我将始终运行“设置统计信息和时间”,如果有任何不妥之处,请尝试另一种方法
  • @DerU 你分享那个链接真酷!很有用!
猜你喜欢
  • 1970-01-01
  • 2012-06-20
  • 2018-11-08
  • 1970-01-01
  • 2022-01-09
  • 1970-01-01
  • 2023-04-07
  • 1970-01-01
  • 2013-07-10
相关资源
最近更新 更多