MS SQL
Question\n\n1795. Rearrange Products Table\nEasy\n\nSQL Schema\nTable: Products\n\n+-------------+---------+\n| Column Name | Type    |\n+-------------+--------
#### Question\n```\n1795. Rearrange Products Table\nEasy\n\nSQL Schema\nTable: Products\n\n+-------------+---------+\n| Column Name | Type    |\n+-------------+---------+\n| product_id  | int     |\n| store1      | int     |\n| store2      | int     |\n| store3      | int     |\n+-------------+---------+\nproduct_id is the primary key for this table.\nEach row in this table indicates the product\'s price in 3 different stores: store1, store2, and store3.\nIf the product is not available in a store, the price will be null in that store\'s column.\n \n\nWrite an SQL query to rearrange the Products table so that each row has (product_id, store, price). If a product is not available in a store, do not include a row with that product_id and store combination in the result table.\n\nReturn the result table in any order.\n\nThe query result format is in the following example:\n\n \n\nProducts table:\n+------------+--------+--------+--------+\n| product_id | store1 | store2 | store3 |\n+------------+--------+--------+--------+\n| 0          | 95     | 100    | 105    |\n| 1          | 70     | null   | 80     |\n+------------+--------+--------+--------+\n\nResult table:\n+------------+--------+-------+\n| product_id | store  | price |\n+------------+--------+-------+\n| 0          | store1 | 95    |\n| 0          | store2 | 100   |\n| 0          | store3 | 105   |\n| 1          | store1 | 70    |\n| 1          | store3 | 80    |\n+------------+--------+-------+\n\nProduct 0 is available in all three stores with prices 95, 100, and 105 respectively.\nProduct 1 is available in store1 with price 70 and store3 with price 80. The product is not available in store2.\n```\n\n#### Answer\n```SQL\nselect product_id, \'store1\' as store, store1 as price from Products p \nwhere store1 is not NULL\nunion\nselect product_id, \'store2\' as store, store2 as price from Products p \nwhere store2 is not NULL\nunion\nselect product_id, \'store3\' as store, store3 as price from Products p \nwhere store3 is not NULL\n```
['MS SQL Server']