Skip to content
Advertisement

Using ORDER BY to pair values in SQL ORACLE

I need to use ORDER BY in a query that uses UNION.

The query returns the following:

CRN Inv_1 Inv_2
GBP -100 -100
GBP -400 -400
GBP -500 -500
GBP -700 -700
GBP -800 -800
GBP -10000 -10000
GBP 100 100
GBP 400 400
GBP 500 500
GBP 700 700
GBP 800 800
GBP 10000 10000

Expected Output:

CRN Inv_1 Inv_2
GBP 100 100
GBP -100 -100
GBP 400 400
GBP -400 -400
GBP 500 500
GBP -500 -500
GBP 700 700
GBP -700 -700

I don’t have an ID to select and order by it and even if I have, I can’t use it since it will appear in the table which I can’t include in the month-end report.

These values will keep changing so they can’t be hard coded to use case statements in order. I tried so many options such as:

If I use ABS(Inv_1 DESC), Inv_1 . This throws an error: ORDER BY ITEM MUST BE THE NUMBER OF A SELEC-LIST EXPRESSION. I’m not using ABS but *-1 instead, since ABS returns the wrong Inv_1/Inv_2

Example:

**Using ABS with UNION doesn’t work : error: ORDER BY ITEM MUST BE THE NUMBER OF A SELEC-LIST EXPRESSION. **

Advertisement

Answer

You didn’t post your query, but – this kind of works for me.

Sample data:

Query with order by clause:


[EDIT]

Aha, now I understand (although you still didn’t post your query).

If there are two tables which return the result set:

Then – if you UNION them and apply order by something that isn’t part of the query – it won’t work:

What can you do? Obviously, add abs(inv_1) into the query:

This works, but – now you have additional column which you don’t really want in the output.

Workaround is to use a CTE or a subquery which contains UNION, but then – in the outer query – you can sort by abs value:

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement