Leetcode Problem 1777. Product's Price for Each Store

1777. Product's Price for Each Store

Leetcode Solutions

Pivoting Table Data in SQL and Pandas

Algorithm

  1. In SQL:
    • Select the product_id.
    • For each store column (store1, store2, store3), use a CASE WHEN statement to check if the store column matches the store name, then select the price.
    • Use the MAX function to ensure that if there are multiple entries for a product-store combination, only one value is returned.
    • Group the results by product_id to get one row per product.
  2. In Pandas:
    • Use the .pivot() method on the products DataFrame.
    • Set index='product_id', columns='store', and values='price' to reshape the DataFrame.
    • The resulting DataFrame will have product_id as the index and store names as column headers, with corresponding prices as values.

erDiagram
    Products {
        int product_id
        enum store
        int price
        product_id store PK
    }

Pivoting Table Data using Conditional Joins in SQL and Melt/Unpivot in Pandas

Ask Question

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

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...