Home > Database > Mysql Tutorial > How to Pivot Long to Wide Format Data in SQLite Using CASE and GROUP BY?

How to Pivot Long to Wide Format Data in SQLite Using CASE and GROUP BY?

Linda Hamilton
Release: 2025-01-10 13:01:46
Original
806 people have browsed it

How to Pivot Long to Wide Format Data in SQLite Using CASE and GROUP BY?

Convert tabular data from long to wide format using SQLite

In data analysis, it is often necessary to convert data from long format (each row represents one record and multiple columns represent different values) to wide format (each record occupies multiple columns). This operation is called pivoting.

We have a table called markdetails with the following structure:

  • studid subjectid marks

    A1 3 50
    A1 4 60
    A1 5 70
    B1 3 60
    B1 4 80
    C1 5 95

There is also a table named student_info with the following structure:

  • studid name

    <code>  A1          Raam
      B1          Vivek
      c1          Alex</code>
    Copy after login

We want to pivot this data into the following wide format:

  • studid name subjectid_3 subjectid_4 subjectid_5

    <code>  A1        Raam        50                60                 70
      B1        Vivek       60                80                NULL
      c1        Alex       NULL              NULL                95</code>
    Copy after login

One way to do this is to use the CASE statement with GROUP BY. The following query will return the required wide format:

<code class="language-sql">SELECT
    si.studid,
    si.name,
    SUM(CASE WHEN md.subjectid = 3 THEN md.marks END) AS subjectid_3,
    SUM(CASE WHEN md.subjectid = 4 THEN md.marks END) AS subjectid_4,
    SUM(CASE WHEN md.subjectid = 5 THEN md.marks END) AS subjectid_5
FROM student_info si
JOIN markdetails md ON
    md.studid = si.studid
GROUP BY si.studid, si.name;</code>
Copy after login

The above is the detailed content of How to Pivot Long to Wide Format Data in SQLite Using CASE and GROUP BY?. 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