[英]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和2记录之间进行交替:
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. 因此,基本上,按相同的行业代码分组,在1条和2条记录之间交替。
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. 有关完整示例,请参见此SQL Fiddle 。 (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: 使用此查询产生的,其中(我假设)您要为您计算SEQ列:
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 请注意,这是乔恩·海勒(Jon Heller)先前回答的衍生产品,可以在http://sqlfiddle.com/#!4/088271/1上在线找到该衍生产品。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.