bugfree Icon
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course

Leetcode Problem 1795. Rearrange Products Table

1795. Rearrange Products Table

Leetcode Solutions

Unpivot Table using UNION in SQL and melt() in Pandas

SQL Algorithm

  1. Use a SELECT statement to retrieve product_id, a constant string as store, and store1 as price from the Products table where store1 is not null.
  2. Repeat step 1 for store2 and store3.
  3. Use the UNION operator to combine the results of the three SELECT statements into one result set.
  4. The final result will have three columns: product_id, store, and price, with rows only for non-null prices.

Pandas Algorithm

  1. Use the melt() function on the products DataFrame, specifying product_id as the identifier variable (id_vars), and the store columns as the variables to unpivot (value_vars).
  2. Rename the variable and value columns to store and price, respectively.
  3. Drop rows with null values in the price column using the dropna() method.
  4. The resulting DataFrame will have the desired long format with product_id, store, and price columns.

erDiagram
    Products {
        int product_id PK
        int store1
        int store2
        int store3
    }

Unpivot Table using CASE Statements in SQL

Ask Question

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

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...