在PL / SQL中组合行

时间:2016-11-03 13:30:48

标签: sql oracle function plsql

Sample Data

我使用PL / SQL提取数据。我想知道如何组合这些行。如您所见,有些单元没有数据,但事实上,数据在下一行可用。

1 个答案:

答案 0 :(得分:0)

跳过你问这个问题的方式,这里是解决方案(看起来很复杂但是有效):

SELECT postcode, 
       replace(REGEXP_REPLACE(replace(LISTAGG(moved_in, '-') WITHIN GROUP (ORDER BY ROWNUM),'No Data Available',''),'([^-]*)(-\1)+($|-)', '\1\3'),'-','')     AS moved_in,
       replace(REGEXP_REPLACE(replace(LISTAGG(moved_out, '-') WITHIN GROUP (ORDER BY ROWNUM),'No Data Available',''),'([^-]*)(-\1)+($|-)', '\1\3'),'-','')    AS moved_out,
       replace(REGEXP_REPLACE(replace(LISTAGG(district, '-') WITHIN GROUP (ORDER BY ROWNUM),'No Data Available',''),'([^-]*)(-\1)+($|-)', '\1\3'),'-','')     AS district,
       replace(REGEXP_REPLACE(replace(LISTAGG(district_new, '-') WITHIN GROUP (ORDER BY ROWNUM),'No Data Available',''),'([^-]*)(-\1)+($|-)', '\1\3'),'-','') AS district_new,
       replace(REGEXP_REPLACE(replace(LISTAGG(country_code, '-') WITHIN GROUP (ORDER BY ROWNUM),'No Data Available',''),'([^-]*)(-\1)+($|-)', '\1\3'),'-','') AS country_code
FROM   test_tab
GROUP BY postcode;

给我输出:

POSTCODE |  MOVED_IN |  MOVED_OUT | DISTRICT    | DISTRICT_NEW | COUNTRY_CODE
-----------------------------------------------------------------------------
B23 6AD  |  16/11/04 |  16/11/04  | Birmingham  | Birmingham   | 00B23

我使用此代码创建测试数据:

CREATE TABLE test_tab
(Postcode VARCHAR2(100),
Moved_in DATE,
Moved_out DATE,
District VARCHAR2(100),
District_New VARCHAR2(100),
Country_code VARCHAR2(100));

INSERT INTO test_tab VALUES ( 'B23 6AD', sysdate, SYSDATE, 'No Data Available', 'No Data Available', '00B23');
INSERT INTO test_tab VALUES ('B23 6AD', sysdate, SYSDATE, 'Birmingham', 'Birmingham', '00B23');
INSERT INTO test_tab VALUES ('B23 6AD', SYSDATE, SYSDATE, 'Birmingham', 'Birmingham', 'No Data Available');