mysql pivot函数
时间: 2023-09-22 22:12:33 浏览: 126
MySQL并没有内置的PIVOT函数,但可以使用条件表达式和聚合函数来实现类似的效果。以下是一个示例查询,演示如何使用条件表达式和聚合函数实现PIVOT功能:
```
SELECT
category,
MAX(CASE WHEN month = 'Jan' THEN sales END) AS Jan,
MAX(CASE WHEN month = 'Feb' THEN sales END) AS Feb,
MAX(CASE WHEN month = 'Mar' THEN sales END) AS Mar,
MAX(CASE WHEN month = 'Apr' THEN sales END) AS Apr,
MAX(CASE WHEN month = 'May' THEN sales END) AS May,
MAX(CASE WHEN month = 'Jun' THEN sales END) AS Jun,
MAX(CASE WHEN month = 'Jul' THEN sales END) AS Jul,
MAX(CASE WHEN month = 'Aug' THEN sales END) AS Aug,
MAX(CASE WHEN month = 'Sep' THEN sales END) AS Sep,
MAX(CASE WHEN month = 'Oct' THEN sales END) AS Oct,
MAX(CASE WHEN month = 'Nov' THEN sales END) AS Nov,
MAX(CASE WHEN month = 'Dec' THEN sales END) AS Dec
FROM
sales_table
GROUP BY category;
```
在这个示例中,假设有一个`sales_table`表,包含列`category`、`month`和`sales`,用于存储不同类别的销售数据。这个查询会将月份作为列名,将每个类别的销售数据进行PIVOT操作,生成一个以类别为行、月份为列的结果集。
请根据你的具体需求修改表名、列名和条件表达式,以适应你的数据结构和查询逻辑。
阅读全文