我正在查询某些值的分组,并根据分组将数据插入到不同的表中。
表名是DETAILS2。该表如下所示:
NUM2 MAT_NUM TRAVEL_DT TRAVEL_TYP TRAVEL_REQ
1-7OR Rail 11-OCT-2016 Train 2
1-7OR Ground 12-OCT-2016 Bus 2
1-7OR Fly 15-0CT-2016 Flight 1
1-72R Rail 11-SEP-2016 Train 2
1-72R Ground 12-SEP-2016 Bus 3
1-72R Fly 15-SEP-2016 Flight 1
我需要先按NUM2,MAT_NUM和TRAVEL_REQ进行分组。
为了实现这一点,我首先编写了以下代码。但是它插入了所有记录。你能帮我修改代码吗?
DECLARE
NUM1 VARCHAR2(50);
NXTNUM1 VARCHAR2(50);
DECIDER VARCHAR2(10);
TYP1 VARCHAR2(50);
CURSOR FET_TYP
IS
SELECT DISTINCT NUM2,
LEAD(NUM2) OVER (ORDER BY NUM2),
CASE WHEN DET.MAT_NUM NOT LIKE '%Fly%' THEN 0 ELSE 1 END DECIDER,
MAT_NUM
FROM DETAILS2
ORDER BY NUM2;
BEGIN
OPEN FET_TYP;
LOOP
FETCH FET_TYP
INTO NUM1,
NXTNUM1,
DECIDER,
TYP1;
EXIT WHEN FET_TYP%NOTFOUND;
IF ((NUM1 = NXTNUM1) AND (DECIDER = 0))
THEN
INSERT INTO TEMP1
VALUES (NUM1, TYP1, 'Ground');
ELSIF ((NUM1 = NXTNUM1) AND (DECIDER = 1))
THEN
INSERT INTO TEMP1
VALUES (NUM1, TYP1, 'Flight');
END IF;
END LOOP;
COMMIT;
CLOSE FET_TYP;
END;
这是最终输出的样子。
NUM2 MAT_NUM TRAVEL_DT TRAVEL_TYP TRAVEL_REQ
1-7OR Ground 12-OCT-2016 Bus 2
1-7OR Fly 15-0CT-2016 Flight 1
1-72R Rail 11-SEP-2016 Train 2
1-72R Ground 12-SEP-2016 Bus 3
1-72R Fly 15-SEP-2016 Flight 1
这些是主列输出以及一些默认值,我将在编写insert语句时插入这些值。第一条记录可以是铁路或地面。 TRAVEL_REQ具有相同值时无关紧要。
答案 0 :(得分:1)
您可以根据自己的条件使用row_number
功能。
select num2,mat_num,travel_dt,travel_typ,travel_req
from (select d.*
,row_number() over(partition by num2,travel_req order by travel_req,mat_num) rn
from details2 d
) x
where rn = 1
将返回的结果集用于insert
所需列到另一个表。