我的数据如下:
ID FROM TO START_CODE END_CODE TYPE
A 01/01/2012 02/02/2012 P E 1
A 12/03/2011 01/01/2012 P X 1
A 01/01/2011 12/03/2011 S X 2
A 01/01/2010 02/02/2010 P E 2
A 12/03/2010 01/01/2010 P X 4
A 01/01/2009 12/03/2009 S X 1
基本上,这是一个客户的信息。 end_code'e'表示护理期的结束,start_code's'表示护理期的开始。起始代码“p”表示日期是延续,“x”的结束代码也是如此。我希望能够返回的数据如下所示:
ID START END Types
A 01/01/2011 02/02/2012 2,1,1
A 01/01/2009 02/02/2010 1,4,2
第一个表的查询看起来与此类似(仅限示例),但是,我有兴趣返回多个客户端,而不仅仅是“A”。
SELECT
A.ID,
A.FROM,
A.TO,
A.START_CODE,
A.END_CODE,
A.Type
WHERE
A.ID = 'A'
我过去曾使用xmlagg来实现类似的东西(即在一个单元格中列出信息),但它实际上是为每个客户端确定单独的开始和结束日期,然后返回我正在努力的类型序列用。作为参考,我的oracle版本是10g,10.2.0.5.0。
感谢您的时间,感谢任何指示或帮助。
编辑包括以下A.B.Cade的建议:
SELECT
t3.MOV_PER_GRO_ID,
t3.f,
t3.MOV_END_DATE,
t3.types,
LENGTH(REGEXP_REPLACE(t3.types,'[^,]')) as "Count"
FROM(
SELECT
sys_connect_by_path(t2.MOV_2000_PLACEMENT_TYPE,',') types,
connect_by_root(t2.MOV_START_DATE) f,
t2.MOV_START_DATE,
t2.MOV_END_DATE,
connect_by_isleaf is_leaf,
t2.MOV_PER_GRO_ID
FROM (SELECT t.*,
lag(t.MOV_START_DATE) over (ORDER BY t.MOV_PER_GRO_ID, t.MOV_START_DATE) nfrom
FROM O_MOVEMENTS t
WHERE t.MOV_PER_GRO_ID IN ('A','B'))t2
START
WITH
t2.MOV_2000_START_REASON = 'S'
CONNECT BY
PRIOR t2.MOV_START_DATE = t2.nfrom
AND PRIOR t2.MOV_PER_GRO_ID = t2.MOV_PER_GRO_ID
AND t2.MOV_2000_START_REASON IN ('P'))t3
where t3.is_leaf=1
根据ABCade的解决方案进行了更新。经过一些调整(再次感谢ABCade),它似乎正在发挥作用。
答案 0 :(得分:2)
尝试:
SELECT t3."ID", t3.f "start", t3."TO" "end", t3.types
FROM (
SELECT sys_connect_by_path(t2."TYPE",',') types,
connect_by_root(t2."FROM") f,
t2."FROM",
t2."TO",
connect_by_isleaf is_leaf ,
t2."ID"
FROM (
SELECT t.*, lag(t."FROM") over (ORDER BY t."FROM") nfrom
FROM table1 t
WHERE t."ID" = 'A'
) t2
START WITH t2."START_CODE" = 'S'
CONNECT BY PRIOR t2."FROM" = t2.nfrom AND t2."START_CODE" = 'P') t3
WHERE is_leaf=1