oracle 行转列的demo
时间: 2023-10-22 16:09:46 浏览: 88
oracle中实现列转行实例
5星 · 资源好评率100%
下面是一个示例,演示如何使用 Oracle SQL 将行转换为列:
假设有一个名为 "employees" 的表,其中包含以下列:employee_id, task_name, task_status。
```sql
-- 创建示例表
CREATE TABLE employees (
employee_id NUMBER,
task_name VARCHAR2(100),
task_status VARCHAR2(20)
);
-- 插入示例数据
INSERT INTO employees VALUES (1, 'Task 1', 'Completed');
INSERT INTO employees VALUES (1, 'Task 2', 'Pending');
INSERT INTO employees VALUES (1, 'Task 3', 'Completed');
INSERT INTO employees VALUES (2, 'Task 1', 'Pending');
INSERT INTO employees VALUES (2, 'Task 2', 'Completed');
INSERT INTO employees VALUES (2, 'Task 3', 'Pending');
-- 使用行转列查询
SELECT
employee_id,
MAX(CASE WHEN task_name = 'Task 1' THEN task_status END) AS task1_status,
MAX(CASE WHEN task_name = 'Task 2' THEN task_status END) AS task2_status,
MAX(CASE WHEN task_name = 'Task 3' THEN task_status END) AS task3_status
FROM employees
GROUP BY employee_id;
```
上述查询会将每个员工的任务状态转换为列,输出结果如下:
```
EMPLOYEE_ID | TASK1_STATUS | TASK2_STATUS | TASK3_STATUS
--------------------------------------------------------
1 | Completed | Pending | Completed
2 | Pending | Completed | Pending
```
请注意,此示例使用了 CASE 表达式和聚合函数 MAX,以将每个任务名称的状态转换为单独的列。你可以根据自己的需求修改列名和条件。
阅读全文