tags:

views:

833

answers:

5

I've got a sql query (using Firebird as the RDBMS) in which I need to order the results by a field, EDITION. I need to order by the contents of the field, however. i.e. "NE" goes first, "OE" goes second, "OP" goes third, and blanks go last. Unfortunately, I don't have a clue how this could be accomplished. All I've ever done is ORDER BY [FIELD] ASC/DESC and nothing else.

Any suggestions?

Edit: I really should clarify: I was just hoping to learn more here. I have it now that I just have multiple select statements defining which to show first. The query is rather large and I was really hoping to learn possibly a more effecient way of doing this: example:

SELECT * FROM RETAIL WHERE MTITLE LIKE 'somethi%' AND EDITION='NE'
UNION 
SELECT * FROM RETAIL WHERE MTITLE LIKE 'somethi%' AND EDITION='OE'
UNION
SELECT * FROM RETAIL WHERE MTITLE LIKE 'somethi%' AND EDITION='OP'
UNION (etc...)
+3  A: 

Add those values to another table with a numeric column for their rank:

Edition  Rank
NE       1
OE       2
OP       3

Join the tables, and sort on the RANK field.

Peter LaComb Jr.
Exactly. If its not a permanent need or changes often, then the OP can use a temp table/ table variable.
StingyJack
+5  A: 

SELECT /other fields/
CASE WHEN 'NE' THEN 1
WHEN "OE" THEN 2
WHEN "OP" THEN 3
ELSE 4 END AS OrderBy
FROM /Tables/
WHERE /conditions/
ORDER BY OrderBy, /other fields/

Pulsehead
Beat me to the punch, +1.
Harper Shelby
Thanks. Glad to know that others use this hack/kludge! makes me feel like a better programmer/dba.
Pulsehead
By the time I started the order by SO warned me of 3 answers.
KP
Is the alias "Sequence" really a good idea? Could it not collide with reserved words on some SQL servers? There is new "CREATE SEQUENCE ..." syntax in Firebird for example.
mghie
I'm not personally familiar with Firebird. I use SQL Server 2005's Enterprise manager. But if Sequence doesn't work for you, then Order By can also be used. In fact, I think I'll edit the reply.
Pulsehead
+9  A: 
Order By Case Edition
    When 'NE' Then 1
    When 'OE' Then 2
    When 'OP' Then 3
    Else 4 End
Charles Bretana
OOH! More streamlined than how I do it. I'll have to remember your solution.
Pulsehead
Indeed - I'd not seen that syntax before.
Peter LaComb Jr.
Case is a wonderful thing
Charles Bretana
A: 

Try:

select *
from MyTable
order by
case [FIELD] 
    when 'NE' then 1
    when 'OE' then 2
    when 'OP' then 3
    when '' then 4
    else 5
end
RedFilter
A: 

Try this:

ORDER BY FIND_IN_SET(EDITION, 'NE,OE,OP,')
FIND_IN_SET() doesn't work in SQL Server 2005. Can you tell me how you did this? I have a kludge solution, but I'm always on the lookout for a more elegant solution.
Pulsehead
CHARINDEX() would work.
recursive