Oracle 10g SQL将行转置为列

时间:2017-08-07 04:56:17

标签: sql oracle

我在Oracle 10g中有一个EMPLOYEE表,其中包括以下字段和数据,其中EMPID是唯一的,grade是组织中员工的当前级别,DOJ是加入组织的日期。

EMPID |NAME|GRADE|DOJ
---------------------------------
111111|AAA |A1   |01-01-2010
---------------------------------
222222|BBB |A3   |01-04-2010
---------------------------------
333333|CCC |A4   |01-03-2010
---------------------------------

EMPLOYEE_GROWTH表,显示每位员工每个连续成绩的入职日期,如下所示

EMPID |GRADE|ENTRY_DT
--------------------------
111111|A1   |01-01-2010
--------------------------
222222|A1   |01-04-2010
--------------------------
222222|A2   |01-07-2012
--------------------------
222222|A3   |01-07-2016
--------------------------
333333|A1   |01-03-2010
--------------------------
333333|A2   |01-07-2012
--------------------------
333333|A3   |01-07-2014
--------------------------
333333|A4   |01-07-2017
--------------------------

现在我想在Oracle中编写一个SQL查询来获取以下报告作为输出

EMPID |GD1|ENTRY_DT1 |GD2|ENTRY_DT2 |GD3|ENTRY_DT3 |GD4|ENTRY_DT4
------------------------------------------------------------------
111111|A1 |01-01-2010|   |          |   |          |   |          
------------------------------------------------------------------
222222|A1 |01-04-2010|A2 |01-07-2012|A3 |01-07-2016|   |          
------------------------------------------------------------------
333333|A1 |01-03-2010|A2 |01-07-2012|A3 |01-07-2014|A4 |01-07-2017
------------------------------------------------------------------

任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:1)

首先使用CASE将行转换为列。然后选择有效值并根据PK对其进行分组。

SELECT 
EMP_ID,
MAX(GD1) AS GD1,
MAX(ENTRY_DT1) AS ENTRY_DT1,
MAX(GD2) AS GD2,
MAX(ENTRY_DT2) AS ENTRY_DT2,
MAX(GD3) AS GD3,
MAX(ENTRY_DT3) AS ENTRY_DT3
FROM
(SELECT EMPID,
CASE WHEN GRADE='A1' THEN GRADE END AS GD1,
CASE WHEN GRADE='A1' THEN ENTRY_DT END AS ENTRY_DT1,
CASE WHEN GRADE='A2' THEN GRADE END AS GD2,
CASE WHEN GRADE='A2' THEN ENTRY_DT END AS ENTRY_DT2,
CASE WHEN GRADE='A3' THEN GRADE END AS GD3,
CASE WHEN GRADE='A3' THEN ENTRY_DT END AS ENTRY_DT3
FROM EMPLOYEE_GROWTH )TR 
GROUP BY EMP_ID

答案 1 :(得分:0)

尝试使用以下网站中提到的技术将行转换为列:

http://www.expert-oracle.com/how-to-convert-rows-into-columns-using-sql-in-oracle/