[sql] TSQL PIVOT MULTIPLE COLUMNS

I have the following table but unsure of whether it is possible to pivot this and retain all the labels.

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

I will admit to not being very good with the use of pivots, so after several attempts resulting in this output:

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

This gives the result:

Ratio    Current Ratio   Gearing Ratio   Performance Ratio
Result   1.294           0.3384          0.0427

I will admit to be feeling very stumped on what to do next to produce the result I need which is:

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

This question is related to sql sql-server tsql pivot

The answer is


Since you want to pivot multiple columns of data, I would first suggest unpivoting the result, score and grade columns so you don't have multiple columns but you will have multiple rows.

Depending on your version of SQL Server you can use the UNPIVOT function or CROSS APPLY. The syntax to unpivot the data will be similar to:

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)

See SQL Fiddle with Demo. Once the data has been unpivoted, then you can apply the PIVOT function:

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;

See SQL Fiddle with Demo. This will give you the result:

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

Examples related to sql

Passing multiple values for same variable in stored procedure SQL permissions for roles Generic XSLT Search and Replace template Access And/Or exclusions Pyspark: Filter dataframe based on multiple conditions Subtracting 1 day from a timestamp date PYODBC--Data source name not found and no default driver specified select rows in sql with latest date for each ID repeated multiple times ALTER TABLE DROP COLUMN failed because one or more objects access this column Create Local SQL Server database

Examples related to sql-server

Passing multiple values for same variable in stored procedure SQL permissions for roles Count the Number of Tables in a SQL Server Database Visual Studio 2017 does not have Business Intelligence Integration Services/Projects ALTER TABLE DROP COLUMN failed because one or more objects access this column Create Local SQL Server database How to create temp table using Create statement in SQL Server? SQL Query Where Date = Today Minus 7 Days How do I pass a list as a parameter in a stored procedure? SQL Server date format yyyymmdd

Examples related to tsql

Passing multiple values for same variable in stored procedure Count the Number of Tables in a SQL Server Database Change Date Format(DD/MM/YYYY) in SQL SELECT Statement Stored procedure with default parameters Format number as percent in MS SQL Server EXEC sp_executesql with multiple parameters SQL Server after update trigger How to compare datetime with only date in SQL Server Text was truncated or one or more characters had no match in the target code page including the primary key in an unpivot Printing integer variable and string on same line in SQL

Examples related to pivot

Laravel, sync() - how to sync an array and also pass additional pivot fields? Construct pandas DataFrame from list of tuples of (row,col,values) How to convert Rows to Columns in Oracle? TSQL PIVOT MULTIPLE COLUMNS Convert Rows to columns using 'Pivot' in SQL Server Efficiently convert rows to columns in sql server MySQL - sum column value(s) based on row from the same table SQL Server Pivot Table with multiple column aggregates Simple way to transpose columns and rows in SQL? MySQL pivot table query with dynamic columns