Leetcode Problem 2253. Dynamic Unpivoting of a Table

2253. Dynamic Unpivoting of a Table

Leetcode Solutions

Dynamic SQL Unpivoting

  1. Set the group_concat_max_len session variable to a large number to ensure that the dynamically created SQL query does not get truncated.
  2. Initialize a variable @sql to NULL.
  3. Use GROUP_CONCAT to concatenate all the SELECT statements for each store column in the Products table, excluding the product_id column.
  4. For each store column, create a SELECT statement that selects the product_id, the store name as store, and the store column as price only where the store column is not NULL.
  5. Use UNION to combine all the SELECT statements into one single query.
  6. Prepare a statement from the dynamically created SQL query stored in @sql.
  7. Execute the prepared statement.
  8. Deallocate the prepared statement.
erDiagram
    Products {
        int product_id PK
        int store_name1
        int store_name2
        int store_namen
    }

Static SQL Unpivoting with UNION ALL

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...