Home > Database > Mysql Tutorial > How Can I Unpivot Data and Retain Column Names in SQL?

How Can I Unpivot Data and Retain Column Names in SQL?

Linda Hamilton
Release: 2025-01-21 04:33:08
Original
240 people have browsed it

How Can I Unpivot Data and Retain Column Names in SQL?

Use the "reverse" operation to reconstruct data and preserve column names

The "reverse" operation is an important tool for reconstructing tabular data. It can convert the data from column-oriented format to row-oriented format. A common scenario is to extract data and column names from the original table.

Consider the following table called StudentMarks, which tracks student performance in different subjects:

姓名 数学 科学 英语
Tilak 90 40 60
Raj 30 20 10

The desired output is a reconstructed table with three columns: name, subject and score:

姓名 科目 分数
Tilak 数学 90
Tilak 科学 40
Tilak 英语 60

To achieve this we can use the "invert" operation as shown below:

<code class="language-sql">select u.name, u.subject, u.marks
from student s
unpivot
(
  marks
  for subject in (Maths, Science, English)
) u;</code>
Copy after login

This query successfully reverses the data in the StudentMarks table while preserving name and account information. The "FOR" clause specifies the column names from which data will be extracted.

As you mentioned, your original query successfully reversed the name and fraction values, but was missing the account column. The modified query solves this problem by including the account column in the final select list.

This solution provides a flexible way to reconstruct tabular data, enabling the extraction of data values ​​and corresponding column names.

The above is the detailed content of How Can I Unpivot Data and Retain Column Names in SQL?. 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