基于table1创建新视图:转换类别列结构并拆分行数据
Solution for Creating the Required View
To achieve the desired view that splits each row of table1 into two rows (one for each category column), you can use UNION ALL to combine two select statements—each pulling one category-value pair along with the original ID.
Here's the SQL code to create the view:
CREATE VIEW split_category_view AS SELECT ID, 'category1' AS category, category1 AS value FROM table1 UNION ALL SELECT ID, 'category2' AS category, category2 AS value FROM table1;
How this works:
- The first
SELECTstatement takes each row fromtable1and maps it to a row wherecategoryis explicitly set to'category1'andvalueis the content of thecategory1column. - The second
SELECTdoes the same forcategory2, creating a row with'category2'as the category and the correspondingcategory2value. UNION ALLcombines these two result sets into a single view, preserving all rows (unlikeUNIONwhich would remove duplicates, which we don't want here).
Example Output:
For your sample data:
| ID | category1 | category2 |
|---|---|---|
| 1 | value1 | value2 |
| 2 | value3 | value4 |
The view will return:
| ID | category | value |
|---|---|---|
| 1 | category1 | value1 |
| 1 | category2 | value2 |
| 2 | category1 | value3 |
| 2 | category2 | value4 |
This approach is straightforward and works across most SQL databases (MySQL, PostgreSQL, SQL Server, etc.).
内容的提问来源于stack exchange,提问作者Nwn
相关产品推荐
相关产品推荐

