ORACLE SQL按列名称与数组排序

时间:2016-02-15 02:24:31

标签: sql oracle

我正在使用Oracle DB。

现在我有这样的数据表:

id | point_id | list_order
1  | 2,3,8    | 3,1,2
2  | 3,1      | 2,1
3  | 1,6      | 2,1

我的问题是,如何根据list_order ASC对数据进行排序? 结果数据应为:

id | point_id | list_order 
1  | 3        | 1
1  | 8        | 2
1  | 2        | 3

2 个答案:

答案 0 :(得分:2)

灵感来自this solution

with mydata(id,point_id,list_order)
as
(
  select 1,'2,3,8','3,1,2' from dual
  union all
  select 2,'3,1','2,1' from dual
  union all
  select 3,'1,6','2,1' from dual
)
SELECT  t1.id,
       REGEXP_SUBSTR(t1.point_id, '([^,])+', 1, t2.COLUMN_VALUE) point_id,
       REGEXP_SUBSTR(t1.list_order, '([^,])+', 1, t2.COLUMN_VALUE) list_order
FROM mydata t1 CROSS JOIN
            TABLE
            (
                CAST
                (
                    MULTISET
                    (
                        SELECT LEVEL
                        FROM DUAL 
                        CONNECT BY LEVEL <= REGEXP_COUNT(t1.point_id, '([^,])+')
                    )
                    AS SYS.odciNumberList
                )
            ) t2
ORDER BY ID,LIST_ORDER;

答案 1 :(得分:-1)

试用Oracle XML:

select  a.id,  
        trim( x.column_value.extract( 'e/text()' ) )  as list_order,
        trim( y.column_value.extract( 'e/text()' ) )  as point_id
 from  table  a
 join  table 
         ( xmlsequence
             ( xmltype
                 (   '<e><e>' 
                 ||  replace( a.list_order, ',', '</e><e>' )
                 ||  '</e></e>' ).extract ( 'e/e' ) 
             )
         )  x  
   on  ( 1=1 )
join  table 
         ( xmlsequence
             ( xmltype
                 (   '<e><e>' 
                 ||  replace( a.point_id, ',', '</e><e>' )
                 ||  '</e></e>' ).extract ( 'e/e' ) 
             )
         )  y  
   on  ( 1=1 )

我找到了一个非常好的链接来解决你的问题。这个男人做了很多尝试解决类似的问题。你可以检查它,并尝试其中任何一个:) http://steve-lyon.blogspot.hk/2013/07/aggregated-lists-decomposing-and.html