Oracle query to put rows at odd number adjacent to even number

只愿长相守 提交于 2019-12-24 17:42:42

问题


I need some help in formulating data in Oracle. I will give an example -

I have a Table Customer with Name column.

Customer
  Name
  Ashish
  Amit
  Sunny
  Bob.

I want to get output in the format where names at odd number are adjacent to names at even number; output would be

Customer
Name1     Name2
Ashish    Amit
Sunny     Bob 

and so on...

I tried following query but it doesn't give me the required output.

select  name, 
  case Mod(rownum,2) 
    when 1  then  name
  end  col1,   
  case Mod(rownum,2) 
    when 0  then  name 
  end  col2
from Customer

回答1:


This ia basically a PIVOT of the data but Oracle10g does not have the pivot function so you will have to replicate it using an aggregate and a CASE statement. If you apply the row_number() over() as well you can transform the data into the result that you want.

select 
  max(case when col = 1 then name end) Name1,
  max(case when col = 0 then name end) Name2
from
(
  select name,  mod(rownum, 2) col,
    row_number() over(partition by mod(rownum, 2) order by name) rn
  from customer
) 
group by rn

See SQL Fiddle with Demo

Result:

|  NAME1 | NAME2 |
------------------
| Ashish |  Amit |
|  Sunny |   Bob |



回答2:


You need to group rows 2 by 2, you could try this:

SELECT MAX(decode(rn/2, floor(rn/2), NAME)) name1, 
       MAX(decode(rn/2, floor(rn/2), '', NAME)) name2
  FROM (SELECT c.*, rownum-1 rn 
          FROM Customer)
GROUP BY floor(rn/2)

The rows are ordered arbitrarily in the subquery. You could use analytics (row_number() OVER (ORDER BY ...)) to get a meaningful order.



来源:https://stackoverflow.com/questions/13837026/oracle-query-to-put-rows-at-odd-number-adjacent-to-even-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!