以下是表格结构: -
Table name: Records
---------------------------------------------------------------
| office ID| transactionName | transactionAmount | Date | uid |
---------------------------------------------------------------
我正在尝试从给定订单办公室ID 2,4,1,3中的上表中获取结果。 我们如何在ORDER BY子句中指定id,以便输出的顺序符合指定。
答案 0 :(得分:3)
您可以使用以下主要定义自定义排序顺序的查询:
SELECT * FROM records
ORDER BY CASE officeID
WHEN 2 THEN 1
WHEN 4 THEN 2
WHEN 1 THEN 3
WHEN 3 THEN 4
ELSE 5
END
答案 1 :(得分:1)
为其提供自定义排序顺序
SELECT [office ID], transactionName, transactionAmount, Date, uid
FROM Records
ORDER BY CASE WHEN [office ID] = '2' THEN '1'
WHEN [office ID] = '4' THEN '2'
WHEN [office ID] = '1' THEN '3'
WHEN [office ID] = '3' THEN '4'
答案 2 :(得分:0)
这是另一种选择......
IF OBJECT_ID('tempdb..#TempTable', 'U') IS NOT NULL DROP TABLE #TempTable
create table #TempTable
(
OfficeID int
)
insert into #TempTable (OfficeID) values (1)
insert into #TempTable (OfficeID) values (2)
insert into #TempTable (OfficeID) values (3)
insert into #TempTable (OfficeID) values (4)
declare @CustomSortOrder varchar(100)
set @CustomSortOrder = '2~4~1~3~'
select * from #TempTable
select *
from #TempTable
order by charindex(convert(char(1), #TempTable.OfficeID) + '~', @CustomSortOrder)