简体   繁体   中英

oracle query alternating records

I have a table that looks like this:

SEQ     TICKER     INDUSTRY
1        AAPL        10
1        FB          10
1        IBM         10
1        CSCO        10
1        FEYE        20
1        F           20
2        JNJ         10
2        CMPQ        10
2        CYBR        10
2        PFPT        10
2        K           20
2        PANW        20

What I need is record with the same industry code, to alternate between the 1 & 2 records like this:

1   AAPL   10
2   IBM    10
1   FB     10
2   CSCO   10
1   FEYE   20
2   PANW   20

So basically, grouped by the same industry code, alternate between the 1 & 2 records.

Can't figure out how.

Use an analytic function to create a row number that starts over for each group (industry and sequence), then sort by that row number.

select seq, ticker, industry
    ,row_number() over (partition by industry, seq order by ticker)custom_order
from stocks
order by industry, custom_order, seq;

See this SQL Fiddle for a full example. (It doesn't perfectly match your example results but either your example results are incorrect or there's something else to this question I don't understand.)

Don't see how you arrived at the example result in your question, but this result:

| SEQ | TICKER | INDUSTRY |
|-----|--------|----------|
|   1 |   AAPL |       10 |
|   2 |   CMPQ |       10 |
|   1 |   CSCO |       10 |
|   2 |   CYBR |       10 |
|   1 |     FB |       10 |
|   2 |    IBM |       10 |
|   1 |    JNJ |       10 |
|   2 |   PFPT |       10 |
|   1 |      F |       20 |
|   2 |   FEYE |       20 |
|   1 |      K |       20 |
|   2 |   PANW |       20 |

Was produced using this query, where (I assume) you want the SEQ column calculated for you:

select
       1 + mod(rn,2) Seq
     , ticker
     , industry
from (
      select
             ticker
           , industry
           , 1+ row_number() over (partition by industry
                                   order by ticker) rn
      from stocks
     ) 
order by industry, rn

Please note this is a derivative of the earlier answer by Jon Heller, this derivative can be found online at http://sqlfiddle.com/#!4/088271/1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM