Ordering SQL query by specific field values

2019-06-15 00:22发布

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...)

标签: sql firebird
9条回答
叛逆
2楼-- · 2019-06-15 00:40

How about this?

SELECT * 
FROM RETAIL
WHERE MTITLE LIKE 'somethi%'
ORDER BY POSITION(EDITION, ' OP OE NE') DESC

If substr is empty string, the result is 1. If no match is found, the result is 0.

Position()

Added in Firebird 2.1

reference: https://firebirdsql.org/refdocs/langrefupd21-intfunc-position.html

查看更多
小情绪 Triste *
3楼-- · 2019-06-15 00:40
SELECT * FROM (

SELECT 1 as Rank, R.* FROM RETAIL R WHERE MTITLE LIKE 'somethi%' AND EDITION='NE'
   UNION ALL
SELECT 2 as Rank, R.* FROM RETAIL R WHERE MTITLE LIKE 'somethi%' AND EDITION='OE'
   UNION ALL
SELECT 3 as Rank, R.* FROM RETAIL R WHERE MTITLE LIKE 'somethi%' AND EDITION='OP'
   UNION ALL (etc...)

) ORDER BY 1
查看更多
家丑人穷心不美
4楼-- · 2019-06-15 00:41
    CREATE TABLE #TMP
(
       ID INT IDENTITY(1,1),
       NAME VARCHAR(100),
)

INSERT INTO #TMP
SELECT 'ASHISH'
UNION ALL
SELECT 'CHANDAN'
UNION ALL
SELECT 'DILIP'
UNION ALL
SELECT 'ESHA'
UNION ALL
SELECT 'FIZA'
UNION ALL
SELECT 'MAHESH'
UNION ALL
SELECT 'VIPUL'
UNION ALL
SELECT 'ANIL'

-- I want to sort NAME column from value 'DILIP' then query will be as bellow

SELECT * FROM #TMP ORDER BY CASE WHEN NAME='DILIP' THEN '1' ELSE NAME END ASC

DROP TABLE #TMP
查看更多
孤傲高冷的网名
5楼-- · 2019-06-15 00:51

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.

查看更多
We Are One
6楼-- · 2019-06-15 00:52
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*/
查看更多
迷人小祖宗
7楼-- · 2019-06-15 00:55

Try this:

ORDER BY FIND_IN_SET(EDITION, 'NE,OE,OP,')
查看更多
登录 后发表回答