Reputation: 675
I am working on a project and I have a weird requirement.
I have a table A
with fields (TechID(Primary Key), Orders (INTEGER NUMBER),Name (Varchar))
.
The values of Orders
can be 0, 1, 2, 3, .......
My task is to display the contents of the table ordered by Orders
field. rows where the Orders
field has a value of 1
are displayed first, followed sequentially by the rest. rows with a value of 0
must be displayed at the end. If all the Orders
field's values are 0 I need to order the table by the TechID
field.
Any ideas about achieving this ? Can this be achieved with a SQL query or should I write a T-Sql script for this ?
Upvotes: 0
Views: 785
Reputation: 76
Dont know if it will work on databases other then oracle's
SELECT * FROM T ORDER BY orders nulls last
Upvotes: 0
Reputation: 74277
That's an easy one:
select *
from A
order by case Orders -- 1. Orders values
when 0 then 2 -- of zero collate after
else 1 -- non-zero Orders values
end , --
Orders , -- 2. Then collate by Orders value proper
TechID -- 3. Then by TechID
Upvotes: 9
Reputation: 52117
Didn't actually test it, but this general idea should work:
SELECT * FROM A
ORDER BY
CASE Orders WHEN 0 THEN 2147483647 ELSE Orders END,
TechID
NOTE: This assumes Orders
is an int
. If its a bigint
use 9,223,372,036,854,775,807 instead.
Upvotes: 3