根据值重新排序列

时间:2013-03-21 18:10:33

标签: oracle

有没有办法根据值重新排序表(或查询)中的列。

例如,在每一行上,FacName应该是第一个,NPI - 第二个,TIN - 第三个和地址 - 第四个。

谢谢你!

enter image description here

2 个答案:

答案 0 :(得分:2)

select col1, col2, col3, col4 from (
  select * from (
    select 
      n, str, row_number() over (partition by n order by 
      decode(substr(str,1,3),'Fac',1,'NPI',2,'TIN',3,'Add',4)) cn 
    from (
      select * from (select t.*, rownum n from t)
      unpivot (str for cn in (col1 as 0, col2 as 0, col3 as 0, col4 as 0))
    )
  )
  pivot (min(str) for cn in (1 as col1, 2 as col2, 3 as col3, 4 as col4))
)
order by n

fiddle

答案 1 :(得分:0)

您希望在列之间移动数据这一事实强烈意味着底层数据模型已损坏且需要进行规范化。修复数据模型比向系统添加另一层复杂性更合适。

话虽如此,你应该可以做类似

的事情
SELECT (CASE WHEN column1 LIKE 'FacilityName%' THEN column1
             WHEN column2 LIKE 'FacilityName%' THEN column2
             WHEN column3 LIKE 'FacilityName%' THEN column3
             WHEN column4 LIKE 'FacilityName%' THEN column4
             ELSE null
         END) column1,
       (CASE WHEN column1 LIKE 'NPI%' THEN column1
             WHEN column2 LIKE 'NPI%' THEN column2
             WHEN column3 LIKE 'NPI%' THEN column3
             WHEN column4 LIKE 'NPI%' THEN column4
             ELSE null
         END) column2,
       (CASE WHEN column1 LIKE 'TIN%' THEN column1
             WHEN column2 LIKE 'TIN%' THEN column2
             WHEN column3 LIKE 'TIN%' THEN column3
             WHEN column4 LIKE 'TIN%' THEN column4
             ELSE null
         END) column3,
       (CASE WHEN column1 LIKE 'Address%' THEN column1
             WHEN column2 LIKE 'Address%' THEN column2
             WHEN column3 LIKE 'Address%' THEN column3
             WHEN column4 LIKE 'Address%' THEN column4
             ELSE null
         END) column4
  FROM( <<your query>> )