我有一个查询,它返回如下输出,
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 fruit_id desc, a.rev_date desc
如何处理这个问题,以便我仍然得到所需的输出,当id和primary id相同时首先显示它们?任何想法都表示赞赏。我尝试过工会等但没有获得所需的o / p。 fruit_id desc的顺序不正确,因为这不是以正确的方式排序。谢谢
NAME FRUIT_ID PRIMARY_FRUIT_ID
--------------------------------------
apple 24 24
orange 24 12
pear 24 7
apple 24 24
kiwi 24 6
apple 24 24
apple 24 24
melon 24 2
grape 0 90
banana 0 45
carrot 0 30
期望的输出
NAME FRUIT_ID PRIMARY_FRUIT_ID
--------------------------------------
apple 24 24
apple 24 24
apple 24 24
apple 24 24
kiwi 24 6
orange 24 12
melon 24 2
pear 24 7
grape 0 90
banana 0 45
carrot 0 30
答案 0 :(得分:2)
您希望生成一个值,以便根据您想要的条件进行排序。
ORDER BY fruit_id desc,
a.rev_date desc,
case when fruit_id = primary_fruit_id then 0 else 1 end
您不会在示例输出中显示日期字段,因此我不知道该日期如何对输出进行分段。我猜测日期比相同的关键值更具相关性"但你可以把它放在任何能给你效果的地方。
ORDER BY fruit_id desc,
case when fruit_id = primary_fruit_id then 0 else 1 end,
a.rev_date desc
ORDER BY case when fruit_id = primary_fruit_id then 0 else 1 end,
fruit_id desc,
a.rev_date desc
答案 1 :(得分:1)
试试这个:
ORDER BY fruit_id desc, abs(fruit_id-PRIMARY_FRUIT_ID) asc