在列表项中选择结果和排序

时间:2016-07-05 16:24:55

标签: sql-server-2008

我想通过在where子句中列出它们来对它们进行排序来显示我的MySQL查询的结果。目前,结果未按列表中的数字顺序列出。

这是我的陈述

SELECT *
FROM subscription
WHERE phone in 
(
    '255769016082',
    '255742594724',
    '255753299742',
    '255759502732',
    '255753839708'
)

1 个答案:

答案 0 :(得分:3)

由于您希望按非顺序顺序按多个值排序,即它们在数值上不是按顺序排列,也不是按顺序正确排序,而是需要对它们应用数值。这是你如何做到的。

if object_id('tempdb..#temp') is not null drop table #temp

create table #temp (phone varchar(20))

insert into #temp (phone) values
('255769016082'),
('255742594724'),
('255753299742'),
('255759502732'),
('255753839708'),
('257538312333')

SELECT * 
FROM #temp
WHERE phone in 
(
    '255769016082',
    '255742594724',
    '255753299742',
    '255759502732',
    '255753839708'
)
ORDER BY
CASE
    WHEN phone = '255769016082' THEN 1
    WHEN phone = '255742594724' THEN 2
    WHEN phone = '255753299742' THEN 3
    WHEN phone = '255759502732' THEN 4
    WHEN phone = '255753839708' THEN 5
END

将来,如果要对非数字字段进行排序,则需要熟悉SQL Server如何处理此问题。

考虑一下

if object_id('tempdb..#char') is not null drop table #char

create table #char(stringField varchar(6))

insert into #char (stringField) values
('a'),
('A'),
('b'),
('B'),
('AB'),
('aB'),
('ab'),
('Ab'),
('ba'),
('Ba'),
('bA'),
('BA')

select * from #char order by stringField asc
select * from #char order by stringField desc