Skip to content
Advertisement

How to create teble 3 from data of table 1 and table 2

t1 (ordered descending):

a comment
512 (ordered desc)
415
310
205
195
150
132
90
74
20
1

t2 (ordered ascending):

b comment
10 (ordered asc)
11
12
13

I would like to create t3:

a (desc) b comment
512 10 (b=asc)
415 11
310 12
205 13
195 13 (b=desc)
150 12
132 11
90 10
74 10 (b=asc)
20 11
1 12

etc.

In table t3, a is data from t1, and b is data from t2.

Advertisement

Answer

You can add a sequence number and then join using arithmetic:

select t1.*, t2.*
from (select t1.*,
             row_number() over (order by a desc) as seqnum
      from t1
     ) t1 left join
     (select t2.*,
             row_number() over (order by which,
                                         case when which = 'a' then b end asc,
                                         b desc
                               ) as seqnum,
             count(*) over () as cnt
      from t2 cross join
           (select 'a' as which from dual union all
            select 'd' as which from dual
           ) x
     ) t2
     on mod(t1.seqnum - 1, t2.cnt) = t2.seqnum - 1
order by t1.seqnum;
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement