根据oracle sql中的条件转置列

时间:2014-03-03 10:27:45

标签: sql oracle

我有一个测试表和这样的记录:

id1    id2   city    state
123    999   GKP      UP
123    999   Bhopal   MP

我希望我的输出像这样:

id1  id2     legal_addr   mailing_addres
123   999     gkp UP       Bhopal MP

请帮助我。谢谢!

1 个答案:

答案 0 :(得分:0)

使用此查询获得所需的结果。

with your_table(id1,id2,city,state) as 
(select 123,999,'gkp','UP' from dual union all
select 123,999,'Bhopal','MP' from dual)
------
-- End of data preparation
------
select id1, 
       id2, 
       min(decode(state, 'UP', city ||' '||state, null)) as legal_add, 
       min(decode(state, 'MP', city ||' '||state, null)) as mailing_add
  from your_table
  where state in ('UP', 'MP')
group by id1, id2 ;

11g及以上也可以使用支点

with your_table(id1,id2,city,state) as 
(select 123,999,'gkp','UP' from dual union all
select 123,999,'Bhopal','MP' from dual)
------
-- End of data preparation
------
select *
  from your_table
pivot (min(city||' '||state) for state in ('UP' as legal_address, 'MP' as mailing_address)) ;

输出:

ID1 ID2 LEGAL_ADDRESS   MAILING_ADDRESS
---------------------------------------------
123 999 gkp UP          Bhopal MP