Home > Database > Mysql Tutorial > How Can I Transpose User-Defined Field Values in SQL?

How Can I Transpose User-Defined Field Values in SQL?

Susan Sarandon
Release: 2025-01-05 02:10:40
Original
200 people have browsed it

How Can I Transpose User-Defined Field Values in SQL?

SQL Transposing Techniques for User-Defined Field Values

In SQL, you may encounter situations where you need to transpose data stored in rows to form columns. One such example is when you have a table like the one described below:

================================================
| Id | UserId | FieldName     | FieldValue     |
=====+========+===============+================|
| 1  | 100    | Username      | John Doe       |
|----+--------+---------------+----------------|
| 2  | 100    | Password      | pass123!       |
|----+--------+---------------+----------------|
| 3  | 102    | Username      | Jane           |
|----+--------+---------------+----------------|
| 4  | 102    | Password      | $ecret         |
|----+--------+---------------+----------------|
| 5  | 102    | Email Address | [email protected] |
------------------------------------------------
Copy after login

To transpose this data into a format where the FieldNames become column headers and the FieldValues form the corresponding row data, you can leverage the following SQL query:

  SELECT t.userid
         MAX(CASE WHEN t.fieldname = 'Username' THEN t.fieldvalue ELSE NULL END) AS Username,
         MAX(CASE WHEN t.fieldname = 'Password' THEN t.fieldvalue ELSE NULL END) AS Password,
         MAX(CASE WHEN t.fieldname = 'Email Address' THEN t.fieldvalue ELSE NULL END) AS Email
    FROM TABLE t
GROUP BY t.userid
Copy after login

However, for this approach to work effectively, you would need to define CASE statements for each expected FieldName value. To enhance flexibility, consider implementing MySQL's Prepared Statement (dynamic SQL) syntax for dynamically generating these CASE statements.

The above is the detailed content of How Can I Transpose User-Defined Field Values 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