복붙노트

[SQL] 모든 맥주를 여러 TSOLUMNS

SQL

모든 맥주를 여러 TSOLUMNS

나는이 피벗 모든 레이블을 유지하기 위해 다음 표하지만 가능 여부를 확신 할 수 있습니다.

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

나는 아주 인 결과 I의 필요성을 생산 옆에 무엇을해야하는지에 난처한 상황에 빠진 느낌이 될 인정할 것이다 :

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

해결법

  1. ==============================

    1.당신은 데이터의 여러 열을 피벗 원하기 때문에, 여러 열을하지 않아도 내가 먼저 결과, 점수와 등급 열을 unpivoting 제안하지만 여러 행이있을 것이다.

    당신은 데이터의 여러 열을 피벗 원하기 때문에, 여러 열을하지 않아도 내가 먼저 결과, 점수와 등급 열을 unpivoting 제안하지만 여러 행이있을 것이다.

    SQL Server의 버전에 따라 당신은 UNPIVOT 기능을 사용하거나 CROSS이 적용됩니다. 데이터를 피벗 해제하는 구문은 유사합니다 :

    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 바이올린을 참조하십시오. 데이터가 피봇 팅되면, 당신은 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 바이올린을 참조하십시오. 이것은 당신에게 결과를 줄 것이다 :

    |  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 |
    
  2. from https://stackoverflow.com/questions/19590799/tsql-pivot-multiple-columns by cc-by-sa and MIT license