这是前一个问题的扩展,Order by depending on 2 col values. 我有一个查询,它返回如下输出,
SELECT DISTINCT a.rev_date ,fruitname,
fruit_id , primary_fruit_id
FROM fruits a, fruit_lookup s,fruit_reference r
WHERE a.id = s.id(+)
and primary_fruit_id = r.fruit_id(+)
AND (fruit_id = 24 or fruit_id = 0)
ORDER BY case when fruit_id = primary_fruit_id then 0 else 1 end,
fruit_id desc,
a.rev_date desc
如何处理这个问题,以便以下面的方式获得所需的输出。因此,只要fruit_id为0,那些行就需要进入10行结果集中的第2行和第5行。如果总计结果大约为50,则每页将有10个结果,而在第2和第5位置,我需要获得如下输出。希望这是有道理的。任何想法都表示赞赏。 THX
NAME FRUIT_ID PRIMARY_FRUIT_ID
--------------------------------------
apple 24 24
apple 24 24
apple 24 24
apple 24 24
orange 24 12
pear 24 7
kiwi 24 6
melon 24 2
grape 0 90
banana 0 45
carrot 0 30
Desired output
NAME FRUIT_ID PRIMARY_FRUIT_ID
--------------------------------------
apple 24 24
grape 0 90
apple 24 24
apple 24 24
banana 0 45
apple 24 24
kiwi 24 6
orange 24 12
melon 24 2
pear 24 7
carrot 0 30
答案 0 :(得分:0)
这比以前的问题复杂得多,所以答案也有点复杂。 这是我设法做的事情:
with t as (
select x.*,
row_number() over (
partition by fid order by decode(fid , pfid, 1, 2), rd desc) rbr
from (
select distinct a.rev_date rd, s.fruitname fn,
a.fruit_id fid, primary_fruit_id pfid
from fruits a left join fruit_lookup s on a.id = s.id
left join fruit_reference r
on primary_fruit_id = r.fruit_id and r.fruit_id in (0, 24) ) x),
ca as (select count(1) cnt from t),
cx as (
select row_number() over (partition by cwm order by lvl) rn, cwm, lvl
from (
select level lvl, case when mod(level, 10) in (2, 5) then 0 else 24 end cwm
from ca connect by level <= cnt*5))
select rd, fn, fid, pfid
from t join cx on cx.rn = t.rbr and cx.cwm = t.fid
order by lvl
您没有提供数据结构和示例行,所以我尝试重现它们以获取原始输入,这里是带有数据和查询的SQLFiddle。
子查询cx
根据您的规则生成数字,然后将这些数字分配给您的原始查询
最终选择使用这些数字对数据进行排序。
一般逻辑是:插入fruit_id = 0的行,在其他行之间编号为2,5,12,15,22 ....