sql case when 行转列
时间: 2024-01-04 17:20:40 浏览: 242
sql server动态行转列.sql
在SQL中,可以使用CASE WHEN语句实现行转列的功能。通过CASE WHEN语句,可以根据条件将一组数据显示在一行上。
下面是一个示例,演示如何使用CASE WHEN语句实现行转列:
假设有一个表格名为sales,包含以下字段:部门id(department_id)、月份(month)和收入(revenue)。
```sql
SELECT department_id,
MAX(CASE WHEN month = 'January' THEN revenue END) AS January,
MAX(CASE WHEN month = 'February' THEN revenue END) AS February,
MAX(CASE WHEN month = 'March' THEN revenue END) AS March,
MAX(CASE WHEN month = 'April' THEN revenue END) AS April,
MAX(CASE WHEN month = 'May' THEN revenue END) AS May,
MAX(CASE WHEN month = 'June' THEN revenue END) AS June,
MAX(CASE WHEN month = 'July' THEN revenue END) AS July,
MAX(CASE WHEN month = 'August' THEN revenue END) AS August,
MAX(CASE WHEN month = 'September' THEN revenue END) AS September,
MAX(CASE WHEN month = 'October' THEN revenue END) AS October,
MAX(CASE WHEN month = 'November' THEN revenue END) AS November,
MAX(CASE WHEN month = 'December' THEN revenue END) AS December
FROM sales
GROUP BY department_id;
```
上述查询将根据部门id将每个月的收入转换为对应的列,并将结果按部门id进行分组。
阅读全文