sql列转行的方法并举例
时间: 2024-03-29 21:40:00 浏览: 96
SQL列转行是将一行中的多个列转换成多行的过程。一种常见的方法是使用UNPIVOT函数。举例如下:
假设有以下表格:
```
CREATE TABLE sales (
id INT PRIMARY KEY,
product_name VARCHAR(50),
jan_sales INT,
feb_sales INT,
mar_sales INT
);
INSERT INTO sales VALUES
(1, 'Product A', 100, 200, 150),
(2, 'Product B', 75, 125, 100),
(3, 'Product C', 50, 75, 25);
```
现在需要将每个产品的每个月销售额转换为单独的行。可以使用以下SQL语句:
```
SELECT id, product_name, month, sales
FROM sales
UNPIVOT (
sales FOR month IN (jan_sales, feb_sales, mar_sales)
) AS unpvt;
```
输出结果为:
```
id product_name month sales
1 Product A jan_sales 100
1 Product A feb_sales 200
1 Product A mar_sales 150
2 Product B jan_sales 75
2 Product B feb_sales 125
2 Product B mar_sales 100
3 Product C jan_sales 50
3 Product C feb_sales 75
3 Product C mar_sales 25
```
这里使用了UNPIVOT函数,将原来的jan_sales、feb_sales、mar_sales三列转换成了month和sales两列。同时保留了产品的id和名称。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![application/x-dosexec](https://img-home.csdnimg.cn/images/20210720083343.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![text/plain](https://img-home.csdnimg.cn/images/20250102104920.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)