我有一个SQL查询(使用Firebird作为RDBMS),我需要通过字段来订购结果,版本。但是,我需要根据该字段的内容进行排序。即“NE”首先出现,“OE”排在第二位,“OP”排在第三位,空白排在最后。不幸的是,我不知道如何实现这一目标。我所做过的只是ORDER BY [FIELD] ASC / DESC而已。
有什么建议吗?
编辑:我真的应该澄清:我只是希望在这里了解更多。我现在拥有它,我只有多个select语句定义哪个首先显示。查询相当大,我真的希望学习一种更有效的方法: 例如:
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...)
答案 0 :(得分:49)
Order By Case Edition
When 'NE' Then 1
When 'OE' Then 2
When 'OP' Then 3
Else 4 End
答案 1 :(得分:6)
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*/
答案 2 :(得分:5)
将这些值添加到另一个表中,并为其等级添加数字列:
Edition Rank
NE 1
OE 2
OP 3
加入表格,然后在RANK字段上排序。
答案 3 :(得分:2)
尝试:
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
答案 4 :(得分:0)
试试这个:
ORDER BY FIND_IN_SET(EDITION, 'NE,OE,OP,')
答案 5 :(得分:0)
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
答案 6 :(得分:0)
怎么样?
SELECT *
FROM RETAIL
WHERE MTITLE LIKE 'somethi%'
ORDER BY POSITION(EDITION, ' OP OE NE') DESC
如果substr为空字符串,则结果为1。 如果未找到匹配项,则结果为0。
Position()
在Firebird 2.1中添加
参考: https://firebirdsql.org/refdocs/langrefupd21-intfunc-position.html
答案 7 :(得分:0)
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
答案 8 :(得分:0)
SELECT (CASE WHEN 'NE' THEN 1
WHEN "OE" THEN 2
WHEN "OP" THEN 3
ELSE 4) as orden,* FROM Retail WHERE MTITLE LIKE 'somethi%'
AND EDITION IN ('NE', 'OE', 'OP', '') ORDER BY Orden