钟二网络头像

钟二网络

探索SQL查询技巧、Linux系统运维以及Web开发前沿技术,提供一站式的学习体验

  • 文章92531
  • 阅读990422
首页 SQL 正文内容

SQL中pivot使用实例

钟逸 SQL 2025-07-22 07:50:32 3

在SQL中,PIVOT操作符可将行数据转换为列数据,这在分析和报告数据时非常有用。以下是一些SQL中PIVOT的使用实例:

从行数据转换到列数据

假设我们有一个表名为“Sales”的销售数据表,其中包含以下列:

| Product | Month | Sales |

|---|---|---|

| Shirt | Jan | 100 |

| Shirt | Feb | 150 |

| Shirt | Mar | 200 |

| Pants | Jan | 150 |

| Pants | Feb | 200 |

| Pants | Mar | 250 |

要将这些行数据转换为列数据,我们可以使用PIVOT操作符:

SELECT Product,

SUM(CASE WHEN Month = 'Jan' THEN Sales ELSE 0 END) AS JanSales,

SUM(CASE WHEN Month = 'Feb' THEN Sales ELSE 0 END) AS FebSales,

SUM(CASE WHEN Month = 'Mar' THEN Sales ELSE 0 END) AS MarSales

FROM Sales

PIVOT (SUM(Sales) FOR Month IN ('Jan', 'Feb', 'Mar')) AS PVT;

结果将如下所示:

| Product | JanSales | FebSales | MarSales |

|---|---|---|---|

| Shirt | 100 | 150 | 200 |

| Pants | 150 | 200 | 250 |

现在,销售数据按产品分类显示在列中,便于分析和报告。

从列数据转换到行数据

PIVOT操作符也可以反向使用,将列数据转换为行数据。例如,如果我们有一个表名为“MonthlySales”的销售数据表,其中包含以下列:

| Product | JanSales | FebSales | MarSales |

|---|---|---|---|

| Shirt | 100 | 150 | 200 |

| Pants | 150 | 200 | 250 |

要将这些列数据转换为行数据,我们可以使用UNPIVOT操作符:

SELECT Product,

Month,

Sales

FROM MonthlySales

UNPIVOT (Sales FOR Month IN (JanSales, FebSales, MarSales));

结果将如下所示:

| Product | Month | Sales |

|---|---|---|

| Shirt | Jan | 100 |

| Shirt | Feb | 150 |

| Shirt | Mar | 200 |

| Pants | Jan | 150 |

| Pants | Feb | 200 |

| Pants | Mar | 250 |

现在,销售数据按产品和月份分类显示在行中,便于进一步分析和处理。

文章目录
    搜索