Home > Database > Mysql Tutorial > How Can I Unpivot Data While Keeping Original Column Names in SQL?

How Can I Unpivot Data While Keeping Original Column Names in SQL?

Patricia Arquette
Release: 2025-01-21 04:51:08
Original
600 people have browsed it

How Can I Unpivot Data While Keeping Original Column Names in SQL?

Keep original column names for data deconvolution

Data deconvolution (Unpivoting) is a process of converting tabular data into another format, where each column becomes a row and its column names become attributes of the row. While this is typically used to reshape data for analysis or visualization, in some cases it can be useful to retain the original column names.

Question:

Given a data table with column names such as Name, Maths, Science and English, how do we deconvolve the data to obtain the following result set?

Name Subject Marks
Tilak Maths 90
Tilak Science 40
Tilak English 60

Solution:

Using SQL’s UNPIVOT clause, we can deconvolve the data while preserving column names:

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

UNPIVOT clause converts the Maths, Science, and English columns into rows, and the scores become the "marks" column in the deconvolved result set. At the same time, the column name remains in the "subject" column.

Example:

Consider the following dataset:

Name Maths Science English
Tilak 90 40 60
Raj 30 20 10

Applying the provided query to this dataset will produce the desired results:

Name Subject Marks
Tilak Maths 90
Tilak Science 40
Tilak English 60
Raj Maths 30
Raj Science 20
Raj English 10

This technique is useful when retaining the original column names is important for further analysis or data processing.

The above is the detailed content of How Can I Unpivot Data While Keeping Original 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