我具有以下表格结构
Area Section Carrying_Engine
A1 S1 Petrol
A2 S1 Petrol
A3 S1 Diesel
A4 S1 Petrol
A5 S2 Diesel
A6 S2 Petrol
问题说明是我们必须显示在S1和S2节下的区域内,发动机是汽油和柴油,输出必须是
Section From_Area To_Area Carrying_Engine
S1 A1 A3 Petrol
S1 A3 A4 Diesel
S1 A4 A5 Petrol
S2 A5 A6 Diesel
PS:无论我们在“携带式引擎”或“部门”中进行转换的哪个位置,都将账面成本添加到先前的“部门”或“携带式引擎”账户中,例如,在第三行中存在一个转换,因此这里从A2移到到A3,我们使用了汽油发动机,在A3点,我们安装了柴油发动机,因此在S1部分,我们将汽油发动机从区域A1移到了A3。同样,在第4-5行中,我们使用汽油引擎从S1部分移动到S2部分,并在A5点处连接了柴油引擎,但是这里我们仅将账面成本添加到S1部分帐户中,因此从A4区域到A5部分,我们使用了汽油引擎在S1节中。
我无法获得解决此问题的逻辑,请指导。
您可以利用分析功能,但是我必须说您必须有一些列来标识该列的顺序,因为oracle不提供记录的自动排序。
我在以下解决方案中使用DATETIME
列来标识列的顺序:
SQL> WITH YOUR_TABLE (Area, Section, Carrying_Engine, DATETIME) AS 2 (SELECT 'A1', 'S1', 'Petrol', SYSDATE - 6 FROM DUAL UNION ALL 3 SELECT 'A2', 'S1', 'Petrol', SYSDATE - 5 FROM DUAL UNION ALL 4 SELECT 'A3', 'S1', 'Diesel', SYSDATE - 4 FROM DUAL UNION ALL 5 SELECT 'A4', 'S1', 'Petrol', SYSDATE - 3 FROM DUAL UNION ALL 6 SELECT 'A5', 'S2', 'Diesel', SYSDATE - 2 FROM DUAL UNION ALL 7 SELECT 'A6', 'S2', 'Petrol', SYSDATE - 1 FROM DUAL) 8 SELECT * -- your query starts from here 9 FROM 10 ( 11 SELECT 12 SECTION, 13 AREA AS FROM_AREA, 14 LEAD(AREA) OVER(ORDER BY DATETIME ) AS TO_AREA, 15 CARRYING_ENGINE 16 FROM 17 ( 18 SELECT 19 T.*, 20 LAG(CARRYING_ENGINE) OVER(ORDER BY DATETIME) AS LEAD_CARRYING_ENGINE 21 FROM YOUR_TABLE T 22 ) 23 WHERE LEAD_CARRYING_ENGINE <> CARRYING_ENGINE 24 OR LEAD_CARRYING_ENGINE IS NULL 25 ) 26 WHERE TO_AREA IS NOT NULL; SECTION | FROM_AREA | TO_AREA | CARRYING_ENGINE ------- | --------- | ------- | --------------- S1 | A1 | A3 | Petrol S1 | A3 | A4 | Diesel S1 | A4 | A5 | Petrol S2 | A5 | A6 | Diesel
干杯!