Home > Database > Mysql Tutorial > How to Pivot Multiple Columns in T-SQL to Transform Financial Ratio Data?

How to Pivot Multiple Columns in T-SQL to Transform Financial Ratio Data?

Mary-Kate Olsen
Release: 2025-01-05 01:54:47
Original
247 people have browsed it

How to Pivot Multiple Columns in T-SQL to Transform Financial Ratio Data?

Pivot Multiple Columns in TSQL

When working with a relational database, it is often necessary to transform data to make it easier to analyze or report on. One way to do this is to pivot the data, which involves rotating rows into columns and vice versa.

Consider the following table that contains financial ratios, results, scores, and grades:

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

To pivot this data and retain all the labels, we need to unpivot the result, score, and grade columns so that each row has one value in each column. This can be achieved using the UNPIVOT function or CROSS APPLY, depending on the version of SQL Server you are using.

Once the data is unpivoted, we can apply the PIVOT function to rotate the rows into columns. The syntax will be similar to the following:

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;
Copy after login

The resulting output will be a table with one row for each ratio, and columns for the current ratio, gearing ratio, performance ratio, total, score, and grade:

RATIO CURRENT RATIO GEARING RATIO PERFORMANCE RATIO TOTAL SCORE GRADE
grade Good Good Satisfactory Good NULL NULL
result 1.29400 0.33840 0.04270 NULL NULL NULL
score 60.00000 70.00000 50.00000 180.00000 NULL NULL

The above is the detailed content of How to Pivot Multiple Columns in T-SQL to Transform Financial Ratio Data?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template