oracle 如何将单个记录转换为垂直行|SQL| [副本]

hgtggwj0  于 2023-05-16  发布在  Oracle
关注(0)|答案(1)|浏览(85)

此问题已在此处有答案

oracle how to transpose columns into rows without UNION(1个答案)
6小时前关闭
我有一个雇员表,其中有数据。
员工:姓名、年龄、工资、职称、课程、加入日期

A,24,2400,Sr,Developer,10-JUN-23  
B,24,2400,Jr,Developer,10-JUN-23
C,24,2400,Tr,Developer,10-JUN-23
D,24,2400,Sr,Developer,10-JUN-23

我编写了一个查询,只获取一条记录

select * from employee where NAME='A';

现在,我想他的所有细节到其他表作为验证数据(插入)
表:Student_A -> column -> DETAILS varchar2(4000)

DETAILS 
A
24
2400
Sr
Developer
10-JUN-23
nafvub8i

nafvub8i1#

您可以将所有列值转换为字符串,然后UNPIVOT

SELECT details
FROM   ( SELECT name,
                TO_CHAR(age) AS age,
                TO_CHAR(salary) AS salary,
                designation,
                course,
                TO_CHAR(join_date, 'YYYY-MM-DD HH24:MI:SS') AS join_date
         FROM   employee
         WHERE  name = 'A')
       UNPIVOT(
         details
         FOR type IN (NAME, AGE, SALARY, DESIGNATION, COURSE, JOIN_DATE)
       );

对于您的示例数据:

CREATE TABLE employee (NAME, AGE, SALARY, DESIGNATION, COURSE, JOIN_DATE) AS
SELECT 'A',24,2400,'Sr','Developer', DATE '2023-06-10' FROM DUAL UNION ALL
SELECT 'B',24,2400,'Jr','Developer', DATE '2023-06-10' FROM DUAL UNION ALL
SELECT 'C',24,2400,'Tr','Developer', DATE '2023-06-10' FROM DUAL UNION ALL
SELECT 'D',24,2400,'Sr','Developer', DATE '2023-06-10' FROM DUAL;

输出:
| 详细信息|
| --------------|
| 一个|
| 二十四|
| 两千四百|
| 锶|
| 开发人员|
| 2019 -06-10 00:00:00|
如果要插入到另一个表中,则使用INSERT INTO table_name (columns) SELECT ...
fiddle

相关问题